C語言用公式求π近似值

終止條件: 某一項: 1 / n+2 < 10 ^ -6;spa

1e-6即0.000001,code

代碼以下:blog

 1 #include<stdio.h>
 2 #include <math.h>
 3 
 4 int main() {
 5     double quarter = 0;
 6     double PI = 0;
 7     int sign = -1;
 8     double term = 1.0;
 9     for ( ; 1.0 / term > 1e-6; ) {
10         // pow(10, -6) == 1e-6
11         sign = -1 * sign;
12         quarter = quarter + sign * (1.0 / term);
13         term = term + 2;
14     }
15     PI = quarter * 4;
16     printf("%.14f\n" ,PI);
17     return 0;
18 }

這裏能算出精確到小數後14位,後面都是0.io

結果:class

3.141590653589692di

相關文章
相關標籤/搜索