Use a formula to Π/4=1-1/3+1/5-1/7 the approximate value of π until the absolute value of an item is found to be less than 10^6 (the item does not accumulate)
Solution: Program:
#include <stdio.h>
#include <math.h>
int main ()
{
int sign = 1;
Double pi = 0.0, n = 1.0, term = 1.0;//term indicates the current item
while (Fabs (term) >= 1e-6)
{
Pi + = term;
n + = 2;
sign =-sign;
term = sign/n;
}
Pi *= 4;
printf ("pi=%10.8f\n", pi);
return 0;
}
Results:
pi=3.14159065
Please press any key to continue ...
The result of this program output is pi=3.14159065, although the output of 8 decimal places, but only the first 5 decimal places 3,14159 is accurate, because the 7th bit is already less than 10^-6, the following items are not cumulative.
Look at the following two different precision programs:
Program 1:
#include <stdio.h>
#include <math.h>
int main ()
{
int sign=1;
int count = 0;
Double pi = 0.0, n = 1.0, term = 1.0;//term indicates the current item
while (Fabs (term) >=1e-6)
{
count++;
Pi + = term;
n + = 2;
sign =-sign;
term = sign/n;
}
Pi *= 4;
printf ("pi=%10.8f\n", pi);
printf ("count=%d\n", count);
return 0;
}
Results:
pi=3.14159065
count=500000
Please press any key to continue ...
Program 2:
#include <stdio.h>
#include <math.h>
int main ()
{
int sign=1;
int count = 0;
Double pi = 0.0, n = 1.0, term = 1.0;//term indicates the current item
while (Fabs (term) >=1e-8)//Change part
{
count++;
Pi + = term;
n + = 2;
sign =-sign;
term = sign/n;
}
Pi *= 4;
printf ("pi=%10.8f\n", pi);
printf ("count=%d\n", count);
return 0;
}
Results:
pi=3.14159263
count=50000000
Please press any key to continue ...
The accuracy is different, the running time is different, the program 2 accuracy is higher, but the running times is 100 times times of the program 1.
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1741580
C: Finding the approximate value of π