2015-04-05 36 views
-1

我正在嘗試運行一個集成程序,但是我一直在計算時纔得到nan。我不知道我的代碼有什麼問題。C++ 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; 

    } 

    } 

能有人幫我這...

+5

使用調試器。 – chris 2015-04-05 18:13:50

回答

0

這是因爲x和y在您的代碼中始終爲0,因爲h是int。當你做(h-i)/ h時,編譯器假定(h-i)是int並且h也是int,所以它也假定比率的結果是int。這個比例是0和1之間,所以當你只用一個int表示,它僅僅是0,該值的兩倍,然後保持爲0 後才編譯器投用試:

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

它工作感謝 – Nathan 2015-04-05 18:32:41

2

隨着

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 a double以避免這種情況。

附註:請,學會正確縮進你的代碼。如果你不這樣做,你最終的同事會爲你活着,他們會是對的。

+0

它的工作感謝 – Nathan 2015-04-05 18:32:24