写一个用矩形法求定积分的通用函数,分别求e^x,sinx,cosx这三个函数从0到1的定积分
#include <stdio.h>
#include <math.h>
double rectangleMethod(double (*func)(double), double a, double b, int n) {
double sum = 0.0;
double width = (b - a) / n;
for (int i = 0; i < n; i++) {
double x = a + i * width;
sum += func(x) * width;
}
return sum;
}
int main() {
int n = 1000;
printf("Integral of e^x from 0 to 1: %f\n", rectangleMethod(exp, 0, 1, n));
printf("Integral of sin(x) from 0 to 1: %f\n", rectangleMethod(sin, 0, 1, n));
printf("Integral of cos(x) from 0 to 1: %f\n", rectangleMethod(cos, 0, 1, n));
return 0;
}
代码解释:
rectangleMethod
函数通过指针调用传递的函数指针来计算定积分。main
函数中,使用rectangleMethod
函数计算e^x
、sin(x)
和cos(x)
的定积分。