求π的近似值

法一:π/4≈1-1/3+1/5-1/7··· 求π的近似值,要求累加到最后一项小于10^(-6)为止

#include<stdio.h>
#include<math.h>
int main()
{
int i, n = 0; double a;
double sum = 0;
for (i = 1; i < pow(10,6); i += 2) {
a = 1 / ((double) i);
sum = sum + pow(-1,n) * a;
n++;
}
printf("π≈%.6f\n", 4*sum);

return 0;
}


法二:π/2≈(2/1)*(2/3)*(4/3)*(4/5)*(6/5)*(6/7)···用前100项之积计算π的值

#include<stdio.h>
int main()
{

double x,product=1;
for (x = 1; x <= 5000000; x++)
product *= ((4 * x* x )/ ((2*x - 1) * (2*x + 1)));
printf("%.6f", product*2);

return 0;
}

 

posted @ 2022-03-23 14:34  小白露  阅读(763)  评论(0)    收藏  举报