利用圆与外切正方形的面积之比来近似计算 PI 的值
而 K 值可通过随机撒点 所占的比模拟近似求得
因为 rand() 函数产生的随机数范围是 0~ 32767 ,RAND_MAX 代表最大的随机数 故
下面有 0 <= X <= 1; 0<= Y <= 1;
当xx + xx <=1时 落在扇形里;
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
//生成0~1 之间的随机数;
double frandom()
{
//srand(time(NULL));
return (double) rand() / RAND_MAX;
}
int main()
{
double x,y,p;
int i,count,n;
srand((unsigned int)time(NULL)) ; //设置种子
scanf("%d",&n);
//模拟随机投点n 次;
count =0;
for(int i=0;i<n;i++)
{
x= frandom();
y= frandom();
// printf("%f %f\n",x,y);
if(sqrt(x*x + y*y)<=1) // 若点位于 扇形内;
count ++;
}
p= 4.0 * count / n; //计算 PI 的近似值
printf("%.4f\n",p); //输出 PI 的近似值
return 0;
}
srand() 函数可产生 0~32767 的随机数 srand() 用来设置 rand() 产生随机数种子
在调用 rand()函数前 如果没有用 srand() 函数设置随机数种子,随机数种子 将自动设成相同值 1;
将会导致 rand ()所产生的随机数都一样,所以在调用 rand()函数时 先利用 srand()设好随机数种子。
通常用 time(NULL) 的返回值做种子 ,time(NULL)的返回值是 国际标准时间公元1970 年1月1日零点 以来经过的秒数。