7-5 Approximately find PI
topic:
This question requires writing a program to find the approximate value of π according to the following formula until the last term is less than the given precision eps.
Input format:
The input gives the precision eps in one line, you can use the following statement to read the input:
scanf("%le", &eps);
Output format:
In one line, output the approximate value of π in the following format (with 5 decimal places):
PI = approximate value
Input sample:
1E-5
Sample output:
PI = 3.14158
Source code:
#include<stdio.h>
int main()
{
double fun(double eps);
double eps;
scanf("%le",&eps);
printf("PI = %.5lf",fun(eps));
}
double fun(double eps)
{
int i;
double a=1,pi=1;
for(i=1;a>=eps;i++){
a=a*i/(2*i+1);
pi+=a;
}
return(2*pi);
}