#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double pi= 0;
long i;
long n;
cout << fixed << showpoint << setprecision(2);
cout << "Enter the value of n: ";
cin >> n;
cout << endl;
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
pi = pi + (1 / (2 * i + 1));
else
pi = pi - (1 / (2 * i + 1));
}
cout << "pi = " << pi << endl;
return 0;
}
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double pi= 0;
long i;
long n;
cout << fixed << showpoint << setprecision(2);
cout << "Enter the value of n: ";
cin >> n;
cout << endl;
pi = 0;
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
pi = pi + (1 % (2 * i + 1));
else
pi = pi - (1 % (2 * i + 1));
}
cout << "pi = " << pi << endl;
pi = 4 * pi;
return 0;
}
I'm still not picking up on the equation. I understand the use of the modulus and the int /int = 0, but what's eluding me is the proper form for the correct equation. Really I don't know why the program uses "i". Is that supposed to be representing an imaginary number?
I've no idea why you introduced modulus to lines 25 and 28.
i is not the imaginary number. It's a way to understand how many times you've gone round a loop. You should stop what you're doing and learn about the "for loop", because if you don't understand it you've got no chance of doing this. It's discussed in the middle of this page: http://www.cplusplus.com/doc/tutorial/control/
I understand the use of the modulus and the int /int = 0, but what's eluding me is the proper form for the correct equation.
Assuming that the formula is right, you can fix the integer division by ensuring that one side of the division is a double. That's easily done by changing 1 to 1.0:
1 2 3 4
if (i % 2 == 0)
pi = pi + (1.0 / (2 * i + 1));
else
pi = pi - (1.0 / (2 * i + 1));