[英]What is wrong with my implementation for integration using Simpson's Rule
[英]Integration by Simpson's Rule
我的任务之一是创建一个使用Simpson的1/3规则来求和的交流程序。 我遇到了无法解决的问题。 可以给有更多经验的人指出正确的方向吗?
从理论上讲,我的代码集成了y = ax ^ 2 + bx + c,其中用户选择a,b,c的值,然后用户选择上下限[d,e]。 然后,用户选择n值,该值将区域分成更多的矩形(我们在课堂上使用的值为100,因此该区域被分为100个矩形)。 之后,它会按照Simpson规则运行并打印出总和。
//n is required number of iterations.
#include<stdio.h>
#include<conio.h>
#include<math.h>
double integral (int a,int b,int c,int d,int e,int n)
int main()
{
double a, b, c, d, e, n;
printf("Please select values for y=ax^2+bx+c");
printf("Please select value for a");
scanf("%d", &a);
printf("Please select value for b");
scanf("%d", &b);
printf("Please select value for c");
scanf("%d", &c);
printf("Please select value for the upper limit");
scanf("%d", &d);
printf("Please select value for the lower limit");
scanf("%d", &e);
printf("Please select the number of rectangles for the Simpson's Rule (Input 100)");
scanf("%n", &n);
int i;
double sum=0,length=(double)(d-e)/(n),ad,bd,cd,dd;
ad=(double)a;
bd=(double)b;
cd=(double)c;
dd=(double)d;
for (i=0;i<n;i++)
{
sum+=(ad*(dd*dd+2*dd*length*i+length*length*i*i)+bd*(dd+length*i)+cd)*length;
printf("the value is = %d",sum);
}
return sum;
}
你为什么这么认为
scanf("%e", &e);
应该那样吗?
scanf()
函数采用格式说明符,以将扫描的输入与之匹配,在这种情况下,您要将值存储在double
变量中,为此您需要"%lf"
说明符,因此所有scanf()
都应改成
scanf("%lf", &whateverDoubleVariableYouWantToStoreTheResultIn);
您无需将给定类型的变量强制转换为相同类型,例如这里
dd=(double)d;
而且,您必须知道, scanf()
返回一个值,您不应忽略它,因为在输入错误的情况下您的程序将无法正常工作,您应该在库手册或C标准中检查scanf()
以更好地了解如何用它。
除了@iharob好的建议:
更改n
类型
// double a, b, c, d, e, n; double a, b, c, d, e; int n;
调整输入代码
// and previous lines if (1 != scanf("%lf", &e)) // %d --> %lf Handle_InputError(); printf("Please select the number of rectangles for the Simpson's ... if (1 != scanf("%d", &n) // %n --> %d Handle_InputError();
调整输出
// printf("the value is = %d",sum); printf("the value is = %e",sum); // or %f
次要位
// int main() int main(void) // or int main(int argc, char *argv[]) // return sum; returning a double here is odd return 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.