topic description
Use the pi/4=1-1/3+1/5-1/7... formula to find the approximate value of pi, when the absolute value of a certain item is less than 10^-6
output format
Approximate values of PI are rounded to six decimal places
problem solving ideas
The code here is easy to understand, just pay attention to i, sum must be defined as a floating point number
This condition is always true if i is of type int
, since 1/i
the result of will be truncated to an integer
#include <stdio.h>
int main()
{
double sum=0,i = 1, k = 1;
double pi;
while (1.0 / i >= 1E-6)
{
sum += k / i;
k = k * (-1);//k取反
i += 2;//等差数列
}
pi = sum * 4;
printf("%.6lf", pi);
return 0;
}