寫一程式可從鍵盤輸入(square,cube,sqrt,cbrt)其中之一的字串, 以及三個數字n,x,y, 並在螢幕上印出該函數在(x,y)區間內的積分值, 而n表示要將該區域切成幾等份來計算. 當輸入之函數名為end時, 結束整個程式.
編譯時請用gcc -lm yours.c來編譯
-l表示要link的程式庫, m表示math(數學)程式庫, 因為sqrt和cbrt這兩個函數 定義在數學程式庫內, 因此編譯時要加上此選項, gcc才能夠正確的連結. 以下是範例程式:
#include <stdio.h>
#include <math.h>
/******************/
* 計算平方 */
******************/
double square(double x) {
return x*x;
}
/******************/
* 計算三次方 */
******************/
double cube(double x) {
return x*x*x;
}
/*********************************************/
/* 計算f()在(x,y)之間以n等份來逼近的積分數值 */
/*********************************************/
double integral(double (*f)(double p), int n, double x, double y) {
// 請填入此處的程式, 請以(*f)(x)來表示f(x)的值
}
int main() {
char fun[100]; // 字元陣列, 下個單元會教到
int n;
double x, y;
double (*f)(double); // pointer to function, 幾個星期後會教到
while (scanf("%99s",fun) != EOF) { // EOF定義於stdio.h內,一般系統上為-1
if (strcmp(fun,"square")==0) {
f = square;
} else if (strcmp(fun,"cube")==0) {
f = cube;
} else if (strcmp(fun,"sqrt")==0) {
f = sqrt;
} else if (strcmp(fun,"cbrt")==0) {
f = cbrt;
} else if (strcmp(fun,"end")==0) {
break;
} else {
printf("Unknown function\n");
continue;
}
scanf("%d%lf%lf",&n,&x,&y);
printf("Integral of %s from %lf to %lf is: %lf\n",fun,x,y,integral(f,n,x,y));
}
return 0;
}