近似计算π值

通过James Gregory的展开式,π/4=1-1/3+1/5-1/7…公式, 计算π近似值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>

double pai(double accuracy)
{
if(accuracy<=0 || accuracy>1) return 3;
int symbol = 1; //项正负标志
int n = 1; //分母项
double pi = 0.0;
do
{
pi += symbol * (1.0 / n);
n += 2;
symbol = -symbol;
}while(1.0/n >= accuracy*0.1 );
return pi*4;
}

int main()
{
double accuracy , pi;
scanf("%lf", &accuracy );
printf("accuracy: %f\n", accuracy);
pi = pai(accuracy);
printf("%f\n", pi);
return 0;
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信