|
Calculate PI from a Series Expansion Using a for
Loop
% cat pi.cpp
// calculate pi from a series
# include <iostream>
# include <iomanip>
using namespace std;
int main()
{
double sum, denom, sign;
int n;
// input data
do
{
cout << "Enter the number of terms (must
be greater than zero): " << endl;
cin >> n;
} while( n <= 0 );
// initialize variables
sum = 0.0;
denom = 1.0;
sign = 1.0;
// calculate pi using a for loop
for (int i=1; i <= n; i++ )
{
// cout << "sign = " << sign
<< " denom = " << denom
// << endl; // diagnostic
sum += sign * 4.0 / denom;
denom += 2.0;
sign = sign * (-1.0);
}
// output the result
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);
cout << "The value of pi from the first "<< n
<< " terms of the series is
" << sum << endl;
}
% g++ pi.cpp
% a.out
Enter the number of terms (must be greater than zero):
10
The value of pi from the first 10 terms of the series is 3.0418
% a.out
Enter the number of terms (must be greater than zero):
10000
The value of pi from the first 10000 terms of the series is 3.1415
|