Approximating PI

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

Original code supplied:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

using namespace 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <iomanip>

using namespace 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.
Hello,

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)

Regards,
Mathes
Worked perfectly with your correction, late night stupid mistakes -_-.
Thanks for your help, very appreciated!
Topic archived. No new replies allowed.