Write a program that computes the value of the mathematical constant π, using the following series:
4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ......
The program should ask for the numbers of terms int n, then compute double pi using the first n terms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <math.h>
usingnamespace std;
int main() {
int i,n;
cout << "Enter the number of terms.";
cin >> n;
double pi;
for ( i =1;i<=n;i++)
pi += pow(-1,i+1) * 4.0 / ( i );
cout << pi;
return 0;
}
There are a couple of errors. First, pi should be initialised with the value 0.
Second, the required series has the denominator 1, 3, 5, 7 etc. but the code above has 1, 2, 3, 4 etc.
You might also look at ways to make this more efficient. Since it may require millions or billions of iterations in order to get a reasonably accurate result, calling a function such as pow() each time is a very expensive use of resources. See if you can do this without the use of pow() or other functions.
*on a side note I wouldn't suggest using pow it is a pretty advanced formula and could slow down your function if you had a really high n. Lets compare run times for 1e6 ( 1million ) Mine takes: .01 seconds Yours takes: .11 seconds so that would mean yours is 11x slower than mine.