Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2506202
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-04-08 17:42:05

    编写一个C程序,用来求出PI的近似值。
    其实其核心思想,就是利用在单位圆中,放置整多边形,当遍数越多,越接近PI,还要使用一些数学公式,我这里就介绍了,就直接上代码了,代码如下:
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <math.h>

  4. double getPI(int n);

  5. int main(int argc, char *argv[])
  6. {
  7.   int n;
  8.   double PI;
  9.   printf("please input accuracy\n");
  10.   scanf("%d",&n);
  11.   PI = getPI(n);
  12.   printf("the similar value of PI is \n%f\n",PI);

  13.   return 0;
  14. }

  15. double getPI(int n)
  16. {
  17.   int div,i=4;
  18.   double b = sqrt(2)/2.0;
  19.   double c = 0.0;
  20.   for(div=0; div<n; div++){
  21.     b = sqrt(2.0 - 2.0*sqrt(1.0 - b*b)) * 0.5;
  22.     i *= 2;
  23.   }
  24.   c = b * i;
  25.   
  26.   return c;
  27. }
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out 
please input accuracy
24
the similar value of PI is
3.141597

阅读(3045) | 评论(0) | 转发(0) |
0

上一篇:常胜将军

下一篇:魔幻方阵

给主人留下些什么吧!~~