【发布时间】:2015-05-15 02:42:13
【问题描述】:
我正在使用梯形规则来计算函数在 0 和无穷大之间的积分。我可以计算给定 N 值的积分值,现在我试图将 N 从 2 循环到给定值,但它不起作用。它不断计算 N 为 2 时的积分值并重复而不是 N 的新值。我认为问题出在 main() 中的 for 循环中。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
double f(double x) {
double a;
a =1/((1+x)*pow(x,0.5));
return a;}
double tra(double upper, double lower, int N) {
double sum, step, integral,lowest;
step=(upper-lower)/(N-1);
lower=lower+step;
if(lower==0) {
lowest=DBL_EPSILON;}
else {
lowest=lower;}
while(lower<upper) {
sum=sum+f(lower);
lower=lower+step;}
integral=step*(sum+(f(upper)/2)+(f(lowest)/2));
sum=0;
return integral;}
main() {
int N;
double upper=DBL_EPSILON*2, lower=0, total=0;
for(N=2;N<20000;N+=100) { /*Here im trying to loop N so that the integral is calculated for increasing values of N*/
while(upper<FLT_MAX) {
total=total+tra(upper, lower, N);
lower=upper;
upper=upper*2;}
printf("Integral is %.10f\n", total);
}
}
【问题讨论】:
-
也许您正在查看内部
while循环,它正在为相同的N运行? -
对不起,我不确定你的意思?
-
您知道在
for循环内有一个嵌套的while循环,不是吗?
标签: c loops for-loop integration numerical-integration