我希望这不是一个平庸的问题,但我在代码中找不到问题。在尝试编译我的代码时,我不断收到错误消息“表达式结果未使用”和“关系比较结果未使用”。 问题在于以下功能:
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);
}
}
}
有谁知道我做错了什么?
答案 0 :(得分: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