My task is to approximate Pi using the following series
pi = 4(1 - 1/3 + 1/5 - 1/7....+ 1/2n-1 + 1/2n+1)
It gives an out of order code and you're supposed to rearrange it into the correct order and then find the bug and remove it
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double pi = 0;
long i, n;
cout << "Enter the value of n" << endl;
cin >> n;
if (i % 2 == 0)
pi = pi + (1 / (2 * i + 1));
else
pi = pi - (1 / (2 * i + 1));
for (i = 0; i < n; i++)
{
pi = 0;
pi = 4 * pi;
}
cout << endl << "pi = " << pi << endl;
return 0;
}
My attempt: The additional "cout's" were to help me try and debug and find the value of pi at each step
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double pi = 0;
long i, n;
cout << "Enter the value of n" << endl;
cin >> n;
for (i = 0; i < n; i++)
{
cout << "pi = " << pi << endl;
if (i % 2 == 0)
{
pi = (pi + (1 / (2 * i + 1)));
cout << "pi = " << pi << endl;
}
else
{
pi = (pi - (1 / (2 * i + 1)));
cout << "pi = " << pi << endl;
}
}
pi = 4 * pi;
cout << endl << "pi = " << pi << endl;
return 0;
}
wheres the problem? I've tried rearranging it every way possible and moving variables around and changing them, but never get anything close to the real value of pi.
the code is correct. The problems are in line 20 and 26.
In 1 / (2 * i + 1) everything is of type int. So the result will be an integer as well.
Since you are interested in double you need at least one double in the formula, i.e. 1.0 / (2 * i + 1)