I need help with a C++ problem

π= 4(1/1- 1/3+ 1/5- 1/7+ 1/9- 1/11+ … 〖(-1)^n /(2n+1)+ …)

How many terms of series (1) you need to use before you get the approximation p of π, where:

a)  p = 3.0 
b)  p = 3.1
c)  p = 3.14
d)  p = 3.141
e)  p = 3.1415
f)  p = 3.14159

I need to use the do-while loop or maybe the for loop. Please help me.

This is what i was trying to do but is not right..

#include <iostream>
using namespace std;

int main()
{
    double c;
    double  i, a=-1, b;
    double s=0, p;

    cout << "Please enter a value for p." << endl;
    cin >> p;

    do
    {
        c=4;
        a= -a;
        b= 2*i+1;
        s+= c*(a/b);
        i++;

    }
    while (s<p+0.05 && s>p-0.05); // i think the condition is wrong.

    cout << "The value of i is: " << i << endl;

    return 0;

}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

use [code] tags, what's the problem?

at first glance i don't see why you set c and a inside of the loop when their values never change, and you never define i, which is probably why your answer is not as expected

Edited 6 Years Ago by ixmike88: n/a

use [code] tags, what's the problem?

at first glance i don't see why you set c and a inside of the loop when their values never change, and you never define i, which is probably why your answer is not as expected

you are right i could just say

do
{

a= -a;

s+= 4*( a / 2*i+1);
i++;

}

but that would not make a difference in my code really.. because im still not getting the correct amount of terms for each value of p and i think is because my "while" statement is wrong

while (s<p+0.05 && s>p-0.05); // i think the condition is wrong.

As ixmike pointed out, c is useless, and most importantly, i is not initialized (and should probably be an integer, int, and not a double).

Now, the input of p and the condition for the loop are not correct. The thing that you have to notice in this problem is that you know the value of Pi = 3.1415926535897932384626433832795 to a very good level of precision anyways. So, the important information to ask at the input is not what p should be, but to what precision you want to approximate Pi. Obviously, from the question, the level of precision required is in the number of significant digits. So, the termination condition should be when the absolute difference between your approximated Pi and the real Pi is less than required precision (±0.5, ±0.05, ±0.005, ±0.0005,...). So, you should ask for how many significant digits are needed, compute the tolerance, and use it as the termination of the loop. Now, if you were to implement this without knowing the actual value of Pi, you could terminate whenever the last change in the approximate value (i.e. the last calculated term of the equation) turns out to be less than the given tolerance.

Edited 6 Years Ago by mike_2000_17: n/a

This article has been dead for over six months. Start a new discussion instead.