About calculating pi

Hi guys! I am new to C++ and I am taking a C++ class in college now. My professor gave us a hw and the problem is "An approximate value of pi can be calculated using the series given below:

pi = 4 [ 1 - 1/3 + 1/5 - 1/7 + 1/9 . . . + ((-1)^n)/(2n + 1) ]

Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation."

I am so lost so I search online for that code and I tried to understand the code and add and delete the thing that I need/don't need.(I will try to write my own code after I understand the whole thing) I understand most of them but when I get to "pi += 4 * (pow(-1,i))/((2*i)+1);" and "pi += 3;" then I am lost. Can anyone explain to me why I need to set the variable "i" = 1 first and why I have to add 3 and pi together after that for loop?

I would appreciate if anyone can help me on this. Thanks!

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

int main()
{
    int terms;
    double pi = 1;

    {
        cout << "Input the number of terms to approximate pi to." << endl;
        cin >> terms;

        if (terms > 0)
        {
            // The series approximates to the value terms times
            for (int i = 1; i <= terms; i++)
            {
                pi += 4 * (pow(-1,i))/((2*i)+1); // 
            }

            // Once loop is complete, add 3 for final pi value
            pi += 3;

            cout << "The approximated value of pi is: " << pi << "." << endl << endl;


        }
        // Stop the program if the user enteres an invalid value.
        else cout << endl << "You did not enter a valid value.\n" << endl;
    }

    return 0;
}
Last edited on
You have the formula typed incorrectly.

It should be (-1)k + 1 / (2k -1)

Or in code
4 * (pow(-1, i + 1.0)) / (2 * i - 1))
Last edited on
No it doesn't. You're simply fixing the incorrect output by adding 3.
Last edited on
Topic archived. No new replies allowed.