c - 程序编译,但收到不正确的答案 - 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 的答案。
解决方案
推荐阅读
- laravel - Laravel 通过 Mac 地址登录
- python - pip install django-import-export 读取超时
- angular - 使用 Angular 和 Jasmine 监听输入按键的测试指令
- python - 如何不在for循环中的语句末尾打印换行符
- html - 通过 ngModel 传递插值
- node.js - 使用 grunt-sass 编译 node-sass,我得到错误“致命错误:“原始”参数必须是函数类型。”
- c++ - C++ - 循环无限运行
- python - 如何在 Web 服务器 (Heroku) 中部署的 PyGSheets 上验证 Google Cloud 服务
- crossfilter - 复杂的减少样本不清楚减少的工作原理
- c# - 根据前 6 个字符组合两个列表