C問題---求pi經典算法

-------------------------------------
典型例題 20:C問題---求pi經典算法。
-------------------------------------
 1    //*******************************
 2    // 經典算法之一:求解PI
 3    // pi.cc
 4    // 公式:PI/4=1-1/3+1/5-1/7+……
 5    //*******************************
 6    #include <iostream>
 7    #include <iomanip>
 8    #include <cmath>
 9   
10    using namespace std;
11   
12    int main()
13    {
14        double s=0,x=1;          //初始值
15        long k=1;
16        int sign=1;
17   
18        while(fabs(x)>1e-8)      //比較前先求絕對值
19            {
20                s+=x;
21                k+=2;
22                sign*=-1;
23                x=sign/double(k); //強制轉換使x得到浮點數值
24            }
25   
26        s*=4;                     //pi=4*(1-1/3+1/5-1/7+……)
27        cout<<"(1)the pi is "
28            <<setiosflags(ios::fixed)
29            <<setprecision(12)
30            <<s<<endl;
31        cout<<"(2)the pi is "
32            <<setiosflags(ios::fixed)
33            <<setprecision(12)
34            <<acos(-1)<<endl;
35        return 0;
36    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章