Finding Pi with an infinite series

i have to calculate pi by using the infinite series:

pi = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 ....

the program is suppose to read in a positive integer and prints a table showing the values of pi approximated by each term. my output is this when i enter 5:

1:4
2:3
3:4
4:4
5:4

which i know is wrong. i have tried so many things to fix it but nothing has helped. i know it is probably something so simple, but i cant seem to find the error. can any one tell me where my error is and how to fix it? thanks in advanced.

my code:

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
38
39
#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    while (n < 1)
    {
        cout << "Error: Enter a positive integer: ";
        cin >> n;
    }

    for (int count = 1; count <= n; count++)
    {
        double pi;
        if (count == 1)
        {
            pi = 4;
            cout << count << ":" << pi << endl;
        }
        else if (count % 2 == 1)
        {
            pi = 4 + (4/((2 * count) - 1));
            cout << count << ":" << pi << endl;
        }
        else
        {
            pi = 4 - (4/((2 * count) - 1));
            cout << count << ":" << pi << endl;
        }

    }

    return 0;
}
an integer division will return an integer so the result will be truncated.
If one of the operands is a double, you will get a more accurate value

eg: pi = 4 - (4.0/((2 * count) - 1)); 4.0 is of type double

thanks Bazzy, that fixed everything. i knew it was truncating, but i havent programmed in 4 months so i couldnt remember how to fix it and i tried everything and was getting frustrated.

thanks again.
Topic archived. No new replies allowed.