2017-05-07 19 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