编写一个C程序,用来求出PI的近似值。
其实其核心思想,就是利用在单位圆中,放置整多边形,当遍数越多,越接近PI,还要使用一些数学公式,我这里就介绍了,就直接上代码了,代码如下:
- #include <string.h>
-
#include <stdio.h>
-
#include <math.h>
-
-
double getPI(int n);
-
-
int main(int argc, char *argv[])
-
{
-
int n;
-
double PI;
-
printf("please input accuracy\n");
-
scanf("%d",&n);
-
PI = getPI(n);
-
printf("the similar value of PI is \n%f\n",PI);
-
-
return 0;
-
}
-
-
double getPI(int n)
-
{
-
int div,i=4;
-
double b = sqrt(2)/2.0;
-
double c = 0.0;
-
for(div=0; div<n; div++){
-
b = sqrt(2.0 - 2.0*sqrt(1.0 - b*b)) * 0.5;
-
i *= 2;
-
}
-
c = b * i;
-
-
return c;
-
}
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out
please input accuracy
24
the similar value of PI is
3.141597
阅读(3094) | 评论(0) | 转发(0) |