急急急！！！！大哥们帮帮我！为什么能这样计算pi值？

littlereddog 2002-03-26 03:38:23

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int main()
{
int i;
int inside = 0;
double val;

srand( (unsigned)time( NULL ) );

for (i=0; i<1000000000; i++)
{
double x = (double)(rand())/RAND_MAX;
double y = (double)(rand())/RAND_MAX;
if ( (x*x + y*y) <= 1.0 )
inside++;
}
val = (double)inside / i;
printf("PI = %.12g\n", val*4);
return 0;
}
...全文
25 点赞 收藏 7

7 条回复

prototype 2002-03-26
to littlereddog ()

i think akiko(弥弥) has explained it very clearly.

what you might not fully understand, i guess, is how the possibility (概率) is calculated. it is actually quite simple:

for example:

double x = (double)(rand())/RAND_MAX;
double y = (double)(rand())/RAND_MAX;

if ( (x*x + y*y) <= 1.0 )
inside++;

zyangxue 2002-03-26

PI=for(n)/for(n+1) 其中的N越大就越精确

kingfighter_han 2002-03-26
up

fangrk 2002-03-26

（公式忘记了）

twist 2002-03-26

akiko 2002-03-26

x*x+y*y=1就是以(0,0)为原点，半径为1的一个圆。

i的范围越大得出的值相对越精确。

prototype 2002-03-26
it is a typical monte carlo (门特卡罗）method. find a basic algorithm book.

1.5w+

C/C++ 非技术区

2002-03-26 03:38