-3

I am using the following code to calculate pi in C but the answer is only being printed to 6dp.

code:

#include<stdio.h>
#include<stdlib.h>

long double calc_pi(int terms) {
    long double result = 0.0F;
    long double sign = 1.0F;

    for (int n = 0; n < terms; n++) {
                result += sign/(2.0F*n+1.0F);
            sign = -sign;
        }

    return 4*result;
}


int main(int argc, char* args[]) {
        long double pi = calc_pi(atoi(args[1]));
    printf("%LF", pi);
}

output:

$ ./pi 10000
3.141493

the 10000 is the number of terms that are used as the code uses an infinite series.

1 Answers1

1

You can add a precision specifier to your printf() format specifier to have it print more digits.

int main(int argc, char* args[]) {
        long double pi = calc_pi(atoi(args[1]));
    printf("%.30LF", pi); /* have it print 30 digits after the decimal point */
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • A great answer; but, I fear that one needs a bit more direction on this matter. This is a great time to mention that floating point numbers are approximations of the real fractional number (and unless one takes care to consider the errors on those approximations, the answer of this series sum will likely contain digits set by the error, instead of by the algorithm) – Edwin Buck Mar 02 '21 at 13:57