Rodrigo Proença
Rodrigo Proença

Reputation: 27

Calculating the value of PI but values are not being adding to variable

Calculating PI can be done using the following formula:

π = 4 - 4/3 + 4/5 -4/7 +4/9 -4/11 ....

The more one goes further the sequence, the better accuracy one can get. My code seems correct, I'm adding the values to variable pi. However, once I print the variable pi I'm getting only zeros. What is wrong?

#include <stdio.h>

int main()
{

    long double pi =0.0;
    long double num= 4.0;
    long double denom= 1.0;
    long int loop;
    long int accuracy;

    accuracy= 400000;

    printf("Accuracy set at: %ld\n", accuracy);
    printf("term\t\t pi\n");

    for(loop=1;loop<=accuracy; loop++)
    {
        if(loop%2 != 0)
        {
            pi += num/denom;
        }
        else{
            pi-= num/denom;
        }
        printf("%ld\t\t%lf\n", loop, pi);
        denom +=2.0;
    }
    return 0;

}

Upvotes: 3

Views: 164

Answers (4)

user6121920
user6121920

Reputation:

Get rid of the long from long double. I tested it out and it seems to be working

Upvotes: 0

rcgldr
rcgldr

Reputation: 28828

Instead of the if / else to handle alternating add and subtract:

for(loop=1;loop<=accuracy; loop++)
{
    pi += num/denom;
    printf("%d\t\t%Lf\n", loop, pi);
    denom += 2.0;
    num = -num;
}

Upvotes: 1

David Pulse
David Pulse

Reputation: 90

You need to make a fitting else if() with it.

for (int loop=1; loop<=accuracy; loop++) {
    if(loop%2 != 0)
      {
        i++;
        if (i%2==0)
          pi += num/denom;
        else
          pi -= num/denom;
      }
    denom++;
}

Upvotes: -1

Brent Washburne
Brent Washburne

Reputation: 13148

My C compiler gives this message on your printf statement:

warning: format specifies type 'double' but the argument has type 'long double' [-Wformat]

Maybe if you use %Lf instead of %lf to print pi?

Upvotes: 4

Related Questions