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