C++ nan不断提出集成

C++ nan keeps coming up with integration

我正在尝试获取一个集成程序 运行 但我在计算时一直获取 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 - ih 都是正数并且 h - i 小于 h,因此结果为整数零。

之后

double x= (h-i)/h;
double y= (h-i)/h;

那么,xy 都是零,从那里开始

中的所有项
  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;