c语言计算PI

c语言计算PI,第1张

数值概率算法具有随机性 建议不用

#include <stringh>

#include <stdioh>

#include <stdlibh>

double getPI(int n);

void main()

{

  double PI;

  int n;

  printf("Please enter the number of random points for test\n");

  scanf("%d",&n);

  PI=getPI(n);

  printf("The similar value of PI is\n%f\n",PI);

  getchar();

}

double getPI(int n)

{

   int inCircle=0;

   float x,y;

   int count=n;

   while(count)

  {

      x=random(101);

      y=random(101);

      if(xx+yy<=10000)

          inCircle++;

      count--;

   }

   return 40inCircle/n;

}

赠送割圆术解法

#include <stringh>

#include <stdioh>

#include <mathh>

double getPI(int n);

void main()

{

  int n;

  double PI;

  printf("Please enter accuracy\n");

  scanf("%d",&n);

  PI=getPI(n);

  printf("The similar value of PI is\n%f\n",PI);

  getchar();

}

double getPI(int n)

{

  int div,i=4;

  double b=sqrt(2)/20;

  double c=00;

  for(div=0;div<n;div++)

  {

      b=sqrt(20-20sqrt(10-bb))05;

      i=i2;

  }

  c=bi;

  return c;

}

给你提个思路:

在这个公式中有几个关键点:

每一项中有一个规律变化数字1,3,5,7,后面应该是9,11;可以用i=1; i+=2;来表示。

每一项中都有规律变化分数相乘1/2 × 3/4 ×这个乘法的截止方法为分母<i。

可以根据以上方法列出计算循环代码,最后一项小于10-6为跳出循环条件;

函数的原理:

pi=1 - 1/2 + 1/4 - 1/6 + 1/8 - 1/10 +

无穷多项之和就等于pi,一般算到最后一项小于一定的数值即可,那就是精度,程序中的2e-6,当然也可以用1e-6或者1e-8等。

以上就是关于c语言计算PI全部的内容,包括:c语言计算PI、C语言编程用公式法求π,应该怎么做、谁详细解释一下C语言求PI编程等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/10215582.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-06
下一篇 2023-05-06

发表评论

登录后才能评论

评论列表(0条)

保存