C ++计算pi的近似值

时间:2018-01-29 03:03:18

标签: c++

人 我将使用以下公式计算pi的近似值: pi = 4 [1 - 1/3 + 1/5 - 1/7 + 1/9。 。 。 +(( - 1)^ n)/(2n + 1)]

我应该使用while循环来导入术语,获取值并一次又一次地重复该过程,直到我导入-1退出。

在我的代码中,第一个输出是正确的,但是当我导入后面的输出时,输出不正确。

我的代码出了什么问题? 谢谢!

#include<iostream>
#include<cmath>
using namespace std;

int main(){
    int terms;
    int terms_;
    double pi = 1 ;

    {
       cout.setf(ios::fixed);
       cout.setf(ios::showpoint);
       cout.precision(3);
       cout<<"Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):"<<endl;
       cin>>terms;

       while(terms > -1)

           {
              for(int i = 1; i<=terms ; i++)
              {
                pi += 4 * (pow(-1.0,i))/((2*i)+1);
               }
             pi += 3
             terms_ = terms + 1;
             cout << "The approximate value of pi using "<< terms_ << " terms is:"<< pi <<endl;

              cout<<"Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):"<<endl;
               cin>>terms;
                 }
             }

}

3 个答案:

答案 0 :(得分:0)

#include<iostream>
#include<cmath>
using namespace std;

int main(){
    int terms;
    int terms_;
    double pi = 1 ;

    {    
       cout.setf(ios::fixed);
       cout.setf(ios::showpoint);
       cout.precision(3);
       cout<<"Enter the value of the parameter 'n' in the Leibniz formula     
       (or -1 to quit):"<<endl;
       cin>>terms;

       while(terms > -1)

           {
              pi = 1;
              for(int i = 1; i<=terms ; i++)
              {
                pi += 4 * (pow(-1.0,i))/((2*i)+1);
               }
             pi += 3;
             terms_ = terms + 1;
             if(terms > 1)
             cout << "The approximate value of pi using "<< terms_ ;
            cout<<"terms is:"<< pi <<endl;

              cout<<"Enter the value of the parameter 'n' in the Leibniz 
             formula (or -1 to quit):"<<endl;
               cin>>terms;
                 }
             }

答案 1 :(得分:-1)

Option Explicit

'Reads a database table from current Active worksheet and paste to output sheet

Function DBReader(DBMarker As Range) As String
    Dim arr(5) As String
    'Read data
    arr(0) = ActiveWorksheet.DBMarker.Value              
    arr(1) = ActiveWorksheet.DBMarker.Offset(1, 1).Value 
    arr(2) = ActiveWorksheet.DBMarker.Offset(2, 1).Value 
    arr(3) = ActiveWorksheet.DBMarker.Offset(0, 2).Value 
    arr(4) = ActiveWorksheet.DBMarker.Offset(1, 2).Value 
    arr(5) = ActiveWorksheet.DBMarker.Offset(2, 2).Value 
    DBReader = arr()
End Function

答案 2 :(得分:-2)

你错过了。

while(term > -1)
{
   pi = 1;
   ...
}

再试一次。