Sign in with
Sign up | Sign in
Your question
Solved

Series of pi with three aproximations in C Lang

Last response: in Applications
Share
December 3, 2012 9:12:43 PM

This is my code for calculating pi. My professor asked that the program's loops end when 3.14,3.141, and 3.1415 appear for the first time, no matter the decimals after the ones asked for. The problem is that it stops at 3.141 two n terms after it actually reaches it the first time, and when it reaches 3.1415 appears it is numerous n terms after the first time it appears as well. Any suggestions to fix this? Is the optimization needed in the condition or in the actual variable declarations? Any suggestions will be appreciated. Written in C Language.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int term=0,a,b,c;
double n=0,sum=0;

printf("\n\tTerm\t\tSum\n\tN\n\n");

do{
sum+=4*pow(-1.,n)/(2*n+1);
n=n++;
printf("\t%d\t\t%f\n",term++,sum);
a=sum*100;
b=sum*1000;
c=sum*10000;
}
while(a!=314);
system("pause");

do{
sum+=4*pow(-1.,n)/(2*n+1);
n=n++;
printf("\t%d\t\t%f\n",term++,sum);
a=sum*100;
b=sum*1000;
c=sum*10000;
}
while(b!=3141);
system("pause");

do{
sum+=4*pow(-1.,n)/(2*n+1) ;
n=n++;
printf("\t%d\t\t%f\n",term++,sum);
a=sum*100;
b=sum*1000;
c=sum*10000;
}
while(c!=31415);
system("pause");
system("cls");
}

Best solution

a b L Programming
December 4, 2012 3:42:16 AM

Thing is, it's calculating correctly, but it's outputing wrong. Let's say it calculated a sum of 3.1414995. It would print it as 3.141500, because it rounds the 7th digit.
Share
December 4, 2012 2:14:08 PM

Best answer selected by Hector3436.
m
0
l
December 4, 2012 2:15:23 PM

Thanks to both of you. I did notice the rounding after doing a verification. Is it possible to increase the amount of decimals in the variable declaration? Thank you
m
0
l
a b L Programming
December 4, 2012 3:15:07 PM

Not really. Rounding errors are always plaguing floating point variables. The only thing you can do is to round down.
m
0
l
!