Infinite pi program

Hi! I have an assignment to write a program for the infinite series of pi:
4 - 4/3 + 4/5 - 4/7 ...
I have most of the assignment complete, but it gives the wrong numbers for pi, so help!

It produces
"Enter number of terms for pi:5
1:4
2:2.66667
3:4.8
4:3.42857
5:4.44444
continue (y/n)?"

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

int main() {
    
    string again="y";
    while(again=="y")
    
    {
        int n,x;
    cout << "Enter number of terms for pi:";
    cin >> n;
    for (x = 1; x <= n; x++){
        double pi;
        if (x == 1)
        {
            pi = 4;
            cout << x << ":" << pi << endl;
        }
        else if (x % 2 == 1)
        {
            pi = 4 + (4.0/((2 * x) - 1));
            cout << x << ":" << pi << endl;
        }
        else
        {
            pi = 4 - (4.0/((2 * x) - 1));
            cout << x << ":" << pi << endl;
        }}
        
    cout << "continue (y/n)?";
        cin >> again;}
    
    
    
    return 0;
    }
Last edited on
Topic archived. No new replies allowed.