我正在尝试运行一个集成程序,但在计算时我不断收到nan。我不知道我的代码有什么问题。
#include <iostream>
#include <cmath>
using namespace std;
int main(){
cout << "For integration up \n";
for (int z=0; z<=5; z++){
int i=1;
float nathan [6] = {pow(10,2), pow(10,3), pow(10,4), pow(10,5),pow(10,6), pow(10,7)};
int h= nathan[z];
int n=0;
double x= (h-i)/h;
double y= (h-i)/h;
double t= 0;
while(n <= h){
if(n == 0){
t += (x/3)*(1/y);
}else if(n==h){
t+= (x/3)*(1/y);
}else if(n%2 ==1){
t+= (4*x/3)*(1/y);
}else{t+= (2*x/3)*(1/y);
}
y= x+y;
n = n+1;
}
cout << "The integration of 1/x for N = "<< nathan[z] <<" is equal to " << t << endl;
}
}
有人可以帮我解决这个问题吗...
与
int i = 1;
int h = nathan[z];
术语
(h - i) / h
调用整数除法,并且由于
h - i
和 h
均为正数,并且 h - i
小于 h
,因此结果为整数零。
之后
double x= (h-i)/h;
double y= (h-i)/h;
然后,
x
和y
都为零,并且从那里中的所有项
if(n == 0){
t += (x / 3) * (1 / y);
} else if(n == h) {
t += (x / 3) * (1 / y);
} else if(n%2 == 1) {
t += (4 * x / 3) * (1 / y);
} else {
t += (2 * x / 3) * (1 / y);
}
结果为零乘以无穷大,这不是一个数字(即 nan)。一旦你掉进那个天坑,你就再也不会回来了。
将
h
设为 double
以避免这种情况。
旁注:请,请,请学会正确缩进你的代码。如果你不这样做,你最终的同事就会活剥你的皮,他们是对的。
这是因为在代码中 x 和 y 始终为 0,因为 h 是 int。当执行 (h-i)/h 时,编译器假定 (h-i) 是 int 并且 h 也是 int,因此它也假定比率的结果是 int。这个比率介于 0 和 1 之间,因此当您仅用 int 表示它时,它只是 0。只有在此之后,编译器才会将此值转换为 double,然后该值仍为 0。 尝试使用:
double x= (h-i)/(double)h;
double y= (h-i)/(double)h;