梯形法则问题
如果你构建并运行代码,你会发现它无法正常工作。这个问题来自一本书(C语言中的问题解决和程序设计)。它给出了2个方程,并想要找到曲线下的近似面积。并添加了调用陷阱n 的值为 2, 4,8, 16, 32, 64, 128。
我的代码的输出是负数和 -nan。 方程为:
g(x) = x^2sinx (a = 0, b = 3.14159)
h(x) = sqrt(4-pow(x.2)) ( a =-2, b=2);
代码为:
#include <stdio.h>
#include <math.h>
void trap(double a,double b, int n, double *areag, double *areah);
double g(double x);
double h(double x);
int main(void)
{
double areag = 0.0, areah = 0.0;
double a1 = 0, b1 = 10;
int n;
for(n=2;n<=128;n*=2){
trap(a1, b1, n, &areag, &areah);
printf("%f %f\n", areag, areah);
}
return(0);
}
double g(double x){
return(pow(x,2)*sin(x));
}
double h(double x){
return(sqrt(4-pow(x,2)));
}
void trap(double a,double b, int n, double *areag, double *areah){
int i, l;
*areag = (b-a)/2*n * ( g(a) + g(b));
for(i = 1; i<=n-1;i++)
*areag += 2*g(i);
*areah = (b-a)/2*n * ( h(a) + h(b));
for(l=1;l<=n-1;l++)
*areah += 2*h(i);
}
If you build and run the code, you will see it doesn't work properly.This question from a book(Problem solving and program design in C).It gives 2 equation and wants find approximating area under a curve.And adds call traps with values for n of 2, 4,8, 16, 32, 64, 128.
Output of my code is negative and -nan.
Equations are:
g(x) = x^2sinx (a = 0, b = 3.14159)
h(x) = sqrt(4-pow(x.2)) ( a =-2, b=2);
And the code is:
#include <stdio.h>
#include <math.h>
void trap(double a,double b, int n, double *areag, double *areah);
double g(double x);
double h(double x);
int main(void)
{
double areag = 0.0, areah = 0.0;
double a1 = 0, b1 = 10;
int n;
for(n=2;n<=128;n*=2){
trap(a1, b1, n, &areag, &areah);
printf("%f %f\n", areag, areah);
}
return(0);
}
double g(double x){
return(pow(x,2)*sin(x));
}
double h(double x){
return(sqrt(4-pow(x,2)));
}
void trap(double a,double b, int n, double *areag, double *areah){
int i, l;
*areag = (b-a)/2*n * ( g(a) + g(b));
for(i = 1; i<=n-1;i++)
*areag += 2*g(i);
*areah = (b-a)/2*n * ( h(a) + h(b));
for(l=1;l<=n-1;l++)
*areah += 2*h(i);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定它的意图是什么,因为你没有解释它应该如何工作,但这部分是取负数的平方根:
啊,现在我明白这就是你想要积分的函数。问题是你需要将集成的范围分成小块,而不是在更大的范围内集成。尝试
I'm not sure what's intended, because you didn't explain how it is supposed to work, but this part is taking the square root of negative numbers:
Ah, now I see that is the function you want to integrate. The problem is that you need to divide the range of integration into small pieces, rather than integrating over a wider range. Try