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.
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 */
}