Okay, I want to make a C program that calculates pi accurately to 4th decimal place (3.1415...). I thought that double is more accurate than float type... Even with a trillion terms (n=trillion), the program cannot go past 3.1414... Can someone help? Am I using an incorrect data type to store my Pi value or is my loops incorrect?
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int n; while(1){ printf("Please enter how many terms (n) you wish to add to approximate Pi: "); scanf("%d", &n); if(n>=1) break; } int x; int count =2; double negSum=0; double posSum=0; double pi = 0; for(x=1;x<=n;x++){ do{ if(x%2==1){ posSum += (4.0)/(2.0*x-1.0); count++; } else{ negSum += (-4.0)/(2.0*x-1.0); count++; } pi = negSum + posSum; } while(pi>3.1414999 && pi<3.14160000); } //pi = negSum + posSum; printf("The value of Pi using your approximation is %f, and the iteration was %d", pi, count); return (EXIT_SUCCESS); } Here is some of my sample input/output:
Please enter how many terms (n) you wish to add to approximate Pi: 98713485 The value of Pi using your approximation is 3.141407, and the iteration was 98713488
while(pi>3.1414999 && pi<3.14160000);? Shouldn’t it be the other way around? Also, you don’t need two different running totals. Just add topi.