关于计算圆周率PI的经典程序

  短短几行代码,却也可圈可点。如把变量s放在PI语句中,避免了在循环条件中调用绝对值函数,还有正负号的处理,都非常巧妙,堪称经典。尤其是处处考虑执行效率的思想令人敬佩。  

 1 /*  pi/4=1-1/3+1/5-1/7+1/9-……  */   
 2 #include <stdio.h>  
 3 int main(){    
 4     int s=1;    
 5     float pi=0.,n=1.,t=1.;   
 6     while(t>1e-6) {    
 7         pi+=s*t;    
 8         n+=2.;    
 9         s=-s;     
10         t=1./n;    
11     }    
12     printf("PI=%f\n",pi*4);   
13     return 0;    
14 } 

 

posted on 2019-07-27 02:24  觉醒的程序  阅读(1061)  评论(0)    收藏  举报

导航

levels of contents