gpt4 book ai didi

c - 我使用辛普森规则进行集成的实现有什么问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:03 27 4
gpt4 key购买 nike

我正在创建一个使用辛普森规则求解积分的 C 程序,我编写了它并运行了它,但在为程序提供值后,它总是返回一个定积分值 0.0000。我重新检查了每一行,看起来不错,这里是代码,如果对这个问题有任何帮助,我们将不胜感激

#include<stdio.h>
#include<math.h>
float ad(int a, int b, int n)
{
float f4, f2, z, v, q4=0, q2=0, d, m, fa, fb;
int w=2, g=1, k=1, j=1;
z=(b-a)/n;
fa=6*pow(a,2)+16*pow(a,3);
fb=6*pow(b,2)+16*pow(b,3);
f4=6*pow(a+z*w,2)+16*pow(a+z*w,3);
f2=6*pow(a+z*g,2)+16*pow(a+z*g,3);
v=fa+fb;
m=v*z;
while(k<=n/2)
{

q4=q4+(z/3)*(4*f4);
w=w+2;
k++;
}
while(j<=(n-2)/2)
{

q2=q2+(z/3)*(2*f2);
g=g+2;
j++;
}
d=m+q4+q2;
return d;
}
main()
{
int x, y, l;
float o;
printf("Enter number x: ");
scanf("%d", &x);
printf("Enter number y: ");
scanf("%d", &y);
printf("Enter an even number: ");
scanf("%d", &l);
if(l%2!=0)
{
printf("The number is odd!\n");
return 1;

}
o=ad(x, y, l);
printf("The aprox integral is es: %f\n", o);
return 0;
}

它也给了我这两个错误:

--------------------Configuration: mingw5 - CUI Debug, Builder Type: MinGW--------------------

Checking file dependency...
Compiling E:\anti simpson\ad.cpp...
[Warning] E:\anti simpson\ad.cpp:29: warning: converting to `int' from `float'
[Warning] E:\anti simpson\ad.cpp:50:2: warning: no newline at end of file
Linking...

Complete Make ad: 0 error(s), 2 warning(s)
Generated E:\anti simpson\ad.exe

最佳答案

你声明你的函数返回 int,但你返回的是一个 float ,结果是:您返回的 float 会被截断,您只会得到 int。

我猜你所有的积分值都在 0 到 1 之间,所以函数只返回 0

只需将 int ad(int a, int b, int n) 更改为 float ad(int a, int b, int n)

编辑:z=(b-a)/n; a、b 和 n 都是整数,你不会在这个除法中得到小数部分。尝试 z=(b-a)/(n * 1.0); 只是将其中一个操作数转换为 float ,这样您也可以获得小数部分

关于c - 我使用辛普森规则进行集成的实现有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com