69,369
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <math.h>
#define N 1000 // 划分1000等分,这个也可以设定为参数,简单点就这样吧。
double f1(double x) // 被积分的函数: sin(x)
{
return sin((double)x);
}
double f2(double x) // 被积分的函数: exp(x)
{
return exp((double)x);
}
double f3(double x) // 被积分的函数: x/(1-x*x)
{
return x/(1-x*x);
}
typedef double (*fptr)(double); // 定义一个函数指针类型fptr,用于指向被积分的函数
double calculate(fptr f, double lower, double upper) // 计算积分。f = 被积分的函数, lower积分下限,upper积分上限
{
double t = 0.0; // 步长
double h = 0.0; // 高度
double result = 0.0; // 积分结果
t = (upper - lower) / N; // 先把步长计算出来
for(int i = 0; i < N; ++i) // 算面积并求和
{
h = (f(lower + i * t) + f(lower + (i + 1) *t) / 2);
result += t * h;
}
return result;
}
int main(int argc,char* argv)
{
double lower = 0.1; // 设定积分下限
double upper = 0.9; // 设定积分上限
printf("Integral of sin(x) between %lf and %lf is: %lf\n", lower, upper, calculate(f1, lower, upper));
printf("Integral of exp(x) between %lf and %lf is: %lf\n", lower, upper, calculate(f2, lower, upper));
printf("Integral of x/(1-x*x) between %lf and %lf is: %lf\n", lower, upper, calculate(f3, lower, upper));
return 0;
}