#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
#define N 30000
void main()
{
double e=0.1,b=0.5,c,d;
long int i; /*i: 正多邊形邊數(shù)*/
float x,y;
int c2=0,d2=0;
clrscr();
puts("***********************************************************");
puts("* This program is to calculate PI approximatively *");
puts("* in two methods. *");
puts("* One method is Regular Polygon Approximating, *");
puts("* the other is Random Number Method. *");
puts("***********************************************************");
puts("\n >> Result of Regular Polygon Approximating:");
for(i=6;;i*=2) /*正多邊形邊數(shù)加倍*/
{
d=1.0-sqrt(1.0-b*b); /*計算圓內(nèi)接正多邊形的邊長*/
b=0.5*sqrt(b*b+d*d);
if(2*i*b-i*e<1e-15) break; /*精度達1e-15則停止計算*/
e=b; /*保存本次正多邊形的邊長作為下一次精度控制的依據(jù)*/
}
printf("---------------------------------------------------------\n");
printf(" >> pi=%.15lf\n",2*i*b); /*輸出π值和正多邊形的邊數(shù)*/
printf(" >> The number of edges of required polygon:%ld\n",i);
printf("---------------------------------------------------------\n");
randomize();
while(c2++<=N)
{
x=random(101); /*x:坐標。產(chǎn)生0到100之間共101個的隨機數(shù)*/
y=random(101); /*y:坐標。產(chǎn)生0到100之間共101個的隨機數(shù)*/
if(x*x+y*y<=10000) /*利用圓方程判斷點是否落在圓內(nèi)*/
d2++;
}
puts("\n >> Result of Random Number Method:");
printf("---------------------------------------------------------\n");
printf(" >> pi=%f\n",4.*d2/N); /*輸出求出的π值*/
printf("---------------------------------------------------------\n");
puts("\n Press any key to quit...");
getch();
}