c语言模拟随机投点计算概率,我写的蒲丰投针的程序(用概率学计算π),有问题求教...

谢谢各位的回答。

此题我已经解决了。

问题是我提议没理解清楚,估计还误导大家了。

蒲丰投针的平行线是一组的,我以为是2条。呵呵。

那么这样的话相交条件改一下,就行了。

下面是我的程序,有兴趣的朋友可以看看。

/*:“在平面上画有一组间距为d的平行线,将一根长度为l(l

求此针与平行线中任一条相交的概率”蒲丰本人证明了,这个概率是=2l/(πd) ,π为圆周率 */

#include

#include

#include

#include

#include

#include

#define N 10000  /*N表示总的投掷次数*/

#define TIME 5    /*做TIME次这样的实验,来平均求pi*/

int main(void)

{

int gdriver = DETECT, gmode, errorcode;

int xmax, ymax;

int x1,x2,y1,y2,i,j;

int counter = 0;

int l = 15,d = 70;

double pi = 0.0,p = 0.0,sum = 0.0;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();

srand((unsigned)time(NULL));

if (errorcode != grOk)

{

printf("Graphics error: %s\n",

grapherrormsg(errorcode));

printf("Press any key to halt:");

getch();

exit(1);

}

xmax = getmaxx();

ymax = getmaxy();

for(j=0;j

{

setcolor(WHITE);

/* draw a diagonal line */

for(i=0;i<=ymax;i=i+d)

{

line(0, 0+i, xmax, 0+i);  /*平行线d=70*/

}

setcolor(RED);

for(i=0;i

{

x1 = rand()%(xmax+1);   /*从0到xmax随机一点*/

y1 = rand()%(ymax+1);

do

{

x2 = rand()%(x1+l)+x1-l;   /*从x1 +- l的范围中随机出一点x2,因为当x2偏离x1超过1个l后,就不可能有长度为l的线段产生*/

}while(x2>x1+l);

y2 = sqrt(l*l - (x2-x1)*(x2-x1))+y1;   /*算出点y,限制条件为长度为l*/

line(x1,y1,x2,y2);

if(y1/d!=y2/d)    /*相交条件*/

{

counter++;

}

}

printf("intersected lines are:%d\n",counter);

p = (double)counter/N;

printf("the probability is :%lf\n",p) ;

pi = (double)2*l/(p*d);

printf("The 'pi' is :%lf",pi);

printf("press any key to clear\n");

counter =0;

sum +=pi;

getchar();

system("cls");

}

printf("The average pi is : %lf",sum/TIME);

getch();

closegraph();

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值