Having issues - with this programming exercise.

The value of p can be approximated by using the following series:
http://i.imgur.com/6z54hSj.png
The following program uses this series to find the approximate value of p. However, the statements are in the incorrect order, and there is also a bug in this program. Rearrange the statements and also find and remove the bug so that this program can be used to approximate p.

i rearranged the code. and added the pi #define.
but lost on the math problem.


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>
#define M_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406 
using namespace std;

Code is not working at this point. 
Little guidance here would be great. 

int main(int argc, const char * argv[])
{
    
    double pi = M_PI;

    long i = 0, n;
    
    cout << "Enter the value of n: " ;
    cin >> n;
    cout << endl;
    
    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;
}

Last edited on
You do not need to add the #define line. I can help you solve it but its better you try yourself. Ask if you have any specific problems.
So this is not for school ( this is out of one of my old text books ) that I am going through thoroughly. To be honest the math part of this problem is beyond me. Also if you or anyone takes the time to to help me solve this. I WILL take the time to understand what was wrong. I just am throwing darts in the dark at this point.
Last edited on
What the program needs to do is to find the sum of all the terms in a series. Since the series is infinite, then realistically it must just include some chosen number of terms from the start of the series, and ignore the rest.

From the image file, we see this:
PI = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 -1/15 + 1/17 - 1/19 + ....)


What does this mean? Well, first get the total of the series in brackets, and the last thing to do is to multiply that by 4. So already we know what the last line of code is (before the output).

The series itself follows a straightforward pattern. The sign alternates between plus and minus, so we must add the first term, subtract the second and so on.

Each term is just a simple fraction, the numerator is always 1, the denominator is just the series of odd numbers starting from 1.

Now you see how it is constructed, getting the program working should be fairly simple.
Topic archived. No new replies allowed.