I am trying to approximate pi using a for loop. The user inputs the number of iterations n, and the program is supposed to get an increasingly accruate value for pi with each additional iteration. I have a nested "if" control structure that checks if "i" is even or odd. However when my loop repeats after the first run, my value for pi is not changing. Pi is staying at 1 in the loop and the final output is 4. I have to use the approximation series:
pi = 4[ 1 - 1/3 + 1/5 +...+ 1/(2n-1) + 1/(2n+1) ].
What am I doing wrong?
int _tmain(int argc, _TCHAR* argv[])
{
double pi = 0;
long i;
int n;
cout << "Enter the value of n: "; //prompt for input
cin >> n; //store input in "n"
cout << endl; //end line
for (i = 0; i < n; i++)
{
if (i % 2 == 0) //if even
pi = pi + (1 / (2 * i + 1));
else //if odd
pi = pi - (1 / (2 * i + 1));
}
pi = 4 * pi; //multiply by 4
cout << endl << "pi = " << pi << endl; //display result
system("Pause"); //pause program
return 0; //close program
The problem is you are using ints
when calculating a floating point number. Read about this here: Why can't I return a double from two ints being divided
So to avoid this you need to do the math with floating point numbers:
pi = pi + (1.0 / (2.0 * i + 1.0));
In fact it is a good idea to always explicitly specify when you intend to use floating point, even if it is unnecessary:
const float pi_real = 3.14159;
const float one = 1.0;
This makes your intention clear and avoids mistakes like this. Here is a live example.