首页 > 解决方案 > 程序编译,但收到不正确的答案 - C 中的辛普森规则集成

问题描述

我正在尝试使用辛普森规则函数计算 C 中从 0 到 PI 的 sin(x) 的积分。我的程序编译,但无论我输入什么,我都会收到 0.0000 的答案。任何人都可以建议吗?

/*Simpson's Rule*/

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


/*sin(x) is the function to be integrated*/
double f(double x){
        return sin(x);
}

/*Define the Simpson's Rule function*/
double simps(double f(double x), double a, double b, double n){
        double h, integral, x, sum=0;
        int i;
        h=fabs(b-a)/n;
                for(i=1; i<n; i++){
                        x=a+i*h;
                if(i%2==0){
                        sum=sum+2*f(x);
                }
                else{
                        sum=sum+4*f(x);
                }
        }
        integral=(h/3)*(f(a)+f(b)+sum);
        return integral;
}

/*Main Program*/
main(){
        int n, i;
        double a = 0.0, b = M_PI, h, x, sum=0, integral;
/*Ask for number of intervals */
        printf("\nEnter the number intervals: ");
        scanf("%d",&n);
/*Print the answer */
        printf("\nThe integral of sin(x) using Simpson's Rule is: %lf\n",integral);
        printf("\nActual value of sin(x) from 0 to pi: 2\n");
}

我知道答案应该接近 2,但无论我输入多少间隔,我都会收到 0.00000 的答案。

标签: c

解决方案


推荐阅读