# 執行結果

``````=============== f(x)=x^4 ================
f(x)     at  2.000              = 16.000
df(x)/dx at  2.000              = 32.002
int(f) from  0.000 to  3.000    = 48.596
=============== f(x)=sin(x) ================
f(x)     at  1.047              =  0.866
df(x)/dx at  1.047              =  0.500
int(f) from  0.000 to  3.142    =  2.000

```

# 程式：diffInt.c

``````#include <stdio.h>
#include <math.h>

#define dx 0.0001
#define pi 3.14159

typedef double (*F1)(double);

// f(x) = x^2 ; f'(x) = 2x;
// f(x) = x   ; f'(x) = 1
// f(x) = x^3 ; f'(x) = 3x^2
// f(x) = x^k ; f'(x) = k x^{k-1}

double power(double x, int k) {
double result = 1.0;
int i;
for (i=1; i<=k; i++)
result *= x;
return result;
}

double p1(double x) {
return power(x,1);
}

double p4(double x) {
return power(x,4);
}

double df(F1 f, double x) {
double dy = f(x+dx)-f(x);
return dy/dx;
}

double intergal(F1 f, double a, double b) {
double sum=0.0;
double x;
for (x = a; x <=b; x+=dx) {
sum += f(x)*dx;
}
return sum;
}

void showDiffInt(F1 f, char *fname, double x, double a, double b) {
printf("=============== f(x)=%s ================\n", fname);
printf("f(x)     at %6.3f          \t= %6.3f\n", x, f(x));
printf("df(x)/dx at %6.3f          \t= %6.3f \n", x, df(f, x));
printf("int(f) from %6.3f to %6.3f \t= %6.3f \n", a, b, intergal(f, a, b));
}

int main() {
F1 f = p4;
showDiffInt(p4, "x^4", 2, 0, 3);
showDiffInt(sin, "sin(x)", pi/3, 0, pi);
system("pause");
}```
```