2017-05-07 17 views
1

我希望這不是一個平庸的問題,但我無法找到我的代碼中的問題。我一直收到錯誤消息「表達式結果未使用」「關係比較結果未使用」當試圖編譯我的代碼時。 問題是與以下功能:未使用的結果錯誤,如果條件c

bool is_inside(double x, double y){ 

    if(sqrt(pow((x-0,5),2)+pow((y-0,5),2))<0,5){ 
     return true; 
    } 
    return false;  
} 

都會調用這個函數:

void estimate_func(unsigned long nsteps, unsigned long nstep_print){ 

     unsigned long i; 
     unsigned long in_circle=0; 
     double x,y; 
     double curr_pi,curr_s; 

     for(i=0;i<nsteps;i++){ 

     x=drand48(); 
     y=drand48(); 

     if(is_inside(x,y)){  // call!!! 
      in_circle++; 
     } 

     if(!(i%(nstep_print+1))){  

      curr_pi=(double) 4*(in_circle/(i+1)); 
      curr_s=4*(sqrt((curr_pi/4)*(1-curr_pi/4)/(double)(i+1))); 

      printf("\t%lu\t%.6lf\t%.6lf\t%.6lf\n", i+1, curr_pi , 
                curr_pi-M_PI, curr_s); 
     }  
     } 
    } 

有沒有人一個想法是什麼,我做錯了什麼?

+5

'xxx <0,5'變成'5' ==>'true' – BLUEPIXY

回答

4

的問題是,從本質上講,是C源代碼不是區域意識。顯然,在您的語言環境中,逗號用作小數點分隔符,因此您將½寫爲0,5。 C不這樣做。它始終使用小數點作爲分隔符,因此½始終爲0.5。

逗號在C中做了一些不同的事情。它實際上是一個獨特的運算符,稱爲逗號運算符。它評估兩個操作數,放棄第一個的結果,並返回第二個的結果。

if((sqrt(pow(((x-0),5),2)+pow(((y-0),5),2))<0),5){ 

其中,evaulating內逗號經營者,給予:

if((sqrt(pow(5,2)+pow(5,2))<0),5){ 

和評估外逗號操作符所以,考慮到運算符優先級,你現在已經是由編譯器所看到簡化爲:

if(5){ 

,編譯器可以告訴是平凡true,因此警告你一下吧。將永遠達不到return false塊。

編寫代碼的正確方法應該是:

bool is_inside(double x, double y){ 

    return (sqrt(pow((x - 0.5), 2) + pow((y - 0.5), 2)) < 0.5); 
} 

注意,我也省略掉了無意義if聲明。這完全一樣,並且更易於閱讀。 C中的比較總是返回1true)或0false),因此其結果可以直接作爲布爾值使用。

我也添加了空格,因爲讓代碼呼吸

+0

姆赫。謝謝,@alk。 :-) –

+0

感謝您的詳盡解釋,但對於替代代碼,我通過了它:) – MyLion

2

你想要做什麼,也許是這樣的:

bool is_inside(double x, double y){ 

    if(sqrt(pow((x-0.5),2)+pow((y-0.5),2))<0.5){ 
     return true; 
    } 
    return false;  
} 

更改,.如果你想表示浮點數(實數)

+0

非常感謝!所以這真的是一個非常愚蠢的問題,對此感到遺憾... – MyLion

0

只要重構你的代碼一點點:

bool is_inside(double x, double y){ 
return sqrt(pow((x-0.5),2) + pow((y-0.5),2)) < 0.5); // changing , to . 
} 


void estimate_func(unsigned long nsteps, unsigned long nstep_print){ 
     unsigned long i, in_circle=0; 
     double x, y, curr_pi, curr_s; 

     for(i = 0; i < nsteps; i++){ 
     x = drand48(); 
     y = drand48(); 

     if(is_inside(x,y)) in_circle++; 

     if(!(i % (nstep_print + 1))){  
      curr_pi = (double) 4 * (in_circle/(i + 1)); 
      curr_s = 4 * (sqrt((curr_pi/4) * (1 - curr_pi/4)/(double)(i + 1))); 
      printf("\t%lu\t%.6lf\t%.6lf\t%.6lf\n", i + 1, curr_pi , 
                curr_pi - M_PI, curr_s); 
     }  
     } 
    } 

總是試圖儘可能減少代碼的行數。美麗的代碼簡潔明瞭。看看這些練習http://divostar.com/learn-c