094.求π的近似值

举报
C语言与CPP编程 发表于 2022/05/03 23:32:20 2022/05/03
【摘要】 #include<stdio.h>#include<math.h>#include<time.h>#include<stdlib.h>#define N 30000void main(){ double e=0.1,b=0.5,c,d; long int i; ...

  
  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<time.h>
  4. #include<stdlib.h>
  5. #define N 30000
  6. void main()
  7. {
  8. double e=0.1,b=0.5,c,d;
  9. long int i; /*i: 正多边形边数*/
  10. float x,y;
  11. int c2=0,d2=0;
  12. clrscr();
  13. puts("***********************************************************");
  14. puts("* This program is to calculate PI approximatively *");
  15. puts("* in two methods. *");
  16. puts("* One method is Regular Polygon Approximating, *");
  17. puts("* the other is Random Number Method. *");
  18. puts("***********************************************************");
  19. puts("\n >> Result of Regular Polygon Approximating:");
  20. for(i=6;;i*=2) /*正多边形边数加倍*/
  21. {
  22. d=1.0-sqrt(1.0-b*b); /*计算圆内接正多边形的边长*/
  23. b=0.5*sqrt(b*b+d*d);
  24. if(2*i*b-i*e<1e-15) break; /*精度达1e-15则停止计算*/
  25. e=b; /*保存本次正多边形的边长作为下一次精度控制的依据*/
  26. }
  27. printf("---------------------------------------------------------\n");
  28. printf(" >> pi=%.15lf\n",2*i*b); /*输出π值和正多边形的边数*/
  29. printf(" >> The number of edges of required polygon:%ld\n",i);
  30. printf("---------------------------------------------------------\n");
  31. randomize();
  32. while(c2++<=N)
  33. {
  34. x=random(101); /*x:坐标。产生0到100之间共101个的随机数*/
  35. y=random(101); /*y:坐标。产生0到100之间共101个的随机数*/
  36. if(x*x+y*y<=10000) /*利用圆方程判断点是否落在圆内*/
  37. d2++;
  38. }
  39. puts("\n >> Result of Random Number Method:");
  40. printf("---------------------------------------------------------\n");
  41. printf(" >> pi=%f\n",4.*d2/N); /*输出求出的π值*/
  42. printf("---------------------------------------------------------\n");
  43. puts("\n Press any key to quit...");
  44. getch();
  45. }

文章来源: blog.csdn.net,作者:程序员编程指南,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_41055260/article/details/124558271

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。