-2

I am using the leibniz method for calculating pi. My program inputs an accuracy number for a calculation of π and then applies the leibniz infinite sum to find an approximate value of π within that accuracy.

I am trying to write a c++ while loop that will input an accuracy number (a double), the initial sum would be equal to zero and initially n would equal zero.

The denominator at n=0, d = 2*n+1 = 1, so the next term would be 4.0/1 = 4.0.

This would then be added to the sum and increment n. If This previous term was greater than the accuracy, the loop would continue.

When the previous term is smaller then the accuracy the number should be outputted and the loop should be exited.

My accuracy is never more than ±0.0001.

My not working code:

while(sum<accuracy)
{
    int n = 0;
    while(n>10) //this is here due to debugging
    {
    sum=-4/(2*n+1);
    n++;
    cout << sum << endl;
    }
}

Question:
I am having a hard time coming up with a working while loop that can do what I described above. How do I create such a loop. Please provide an example with explanation.

user2444074
  • 137
  • 3
  • 6
  • 14

1 Answers1

0

Make sure that your sum-variable is float/double. It is like our friend commentet you are victim of integer division

double sum;

while(sum<accuracy){
    int n=0;
    while(n>10)
    {
        sum=-4.0/(2.0*n+1.0);
        n++;
        cout << sum << endl;
    }
}
Hicham
  • 67
  • 1
  • 2
  • 8