c语言,计算sin(x)在区间[0,3.14]上的定积分,并输出结果。
时间: 2024-06-04 13:10:28 浏览: 133
根据数值积分的方法,可以使用梯形法或者辛普森法进行计算,具体实现可以参考以下代码:
#include <stdio.h>
#include <math.h>
double f(double x)
{
return sin(x);
}
double trapezoid(double a, double b, double n)
{
double h = (b - a) / n;
double sum = 0;
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += f(x);
}
sum += (f(a) + f(b)) / 2;
return sum * h;
}
double simpson(double a, double b, double n)
{
double h = (b - a) / n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += f(x) * ((i % 2 == 0) ? 2 : 4);
}
return sum * h / 3;
}
int main()
{
double a = 0, b = 3.14;
int n = 1000;
printf("Using Trapezoid Rule: %lf\n", trapezoid(a, b, n));
printf("Using Simpson's Rule: %lf\n", simpson(a, b, n));
return 0;
}
使用梯形法得到的结果约为2,使用辛普森法得到的结果约为1.999997。
阅读全文