用π/4 ≈ 1 - 1/3 + 1/5 - 1/7 +... 公式求π的近似值,直到最后一项的绝对值小于10^6为止。
#include <stdio.h> #include <math.h> int main(){ int n=1; double ans=0,tmp = 1.0; while(n<=pow(10,6)){ ans = ans + tmp/n; n = n+2; tmp = -1*tmp; } ans = ans+tmp/n; //最后一个要小于10的-6次方 ans = 4*ans; printf("%f",ans); return 0; }