随机游走问题。程序有错误。
#include <stdio.h>#include <stdlib.h>
#include <time.h>
#include <math.h>
#define PI 3.14159265
#define PP(a) (PI*a/180)
void main()
{
int i,box1,box2,box3,box4,k,Direction;
float x,y;
box1=box2=box3=box4=0;
srand((unsigned)time(NULL));
for(i=1;i<=10000;i++)
{ x=y=0.0;
k=0;
while(k++<500)
{
Direction=rand()%16;
if(y>=50) Direction+=8;
if(y<=-50) Direction-=8;
if(x>=60) Direction+=8;
if(x<=-60) Direction-=8;
switch(Direction)
{
case 0: x+=1;break;
case 1: y+=sin(PP(30));x+=cos(PP(30));break;
case 2: y+=sin(PP(45));x+=cos(PP(45));break;
case 3: y+=sin(PP(60));x+=cos(PP(60));break;
case 4: y+=1;break;
case 5: x-=sin(PP(30));y+=cos(PP(30));break;
case 6: x-=sin(PP(45));y+=cos(PP(45));break;
case 7: x-=sin(PP(60));y+=cos(PP(30));break;
case 8: x-=1;break;
case 9: y-=sin(PP(30));x-=cos(PP(30));break;
case 10: y-=sin(PP(45));x-=cos(PP(45));break;
case 11: y-=sin(PP(60));x-=cos(PP(60));break;
case 12: y-=1;break;
case 13: x+=sin(PP(30));y-=cos(PP(30));break;
case 14: x+=sin(PP(45));y-=cos(PP(45));break;
case 15: x+=sin(PP(60));y-=cos(PP(60));break;
}
if((fabs(x-40)+fabs(y-40))<=1) { box1++;break;}
if((fabs(x-20)+fabs(y+20))<=1) { box2++;break;}
if((fabs(x+45)+fabs(y-50))<=1) { box3++;break;}
if((fabs(x+30)+fabs(y-42))<=1) { box3++;break;}
}
}
printf("%d %d %d %d",box1,box2,box3,box4);
getch();
}
附件里面的那个编程题目是这个题和图解;
作业.rar
(127.97 KB)