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

短短几行代码,却也可圈可点。如把变量s放在PI表达式中,还有正负值的处理,都堪称经典。尤其是处处考虑执行效率的思想令人敬佩。

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

猜你喜欢

转载自www.cnblogs.com/AwakenCode/p/11253669.html