本文主要是介绍简陋的龟兔赛跑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//模拟龟兔赛跑
//先到达30为胜利者
#include<iostream>
#include<string>
#include<ctime>
#include<cmath>
using namespace std;
int getRand(int num)
{
return (rand()%num+1);
}
int move_tortoise(int num)
{
if (num>=1&&num<=5)
return 3;
if (num>=6&&num<=7)
return -6;
if (num>=8&&num<=10)
return 1;
}
int move_hare(int num)
{
if (num>=1&&num<=2)
return 0;
if (num>=3&&num<=4)
return 9;
if (num==5)
return -12;
if (num>=6&&num<=8)
return 1;
if (num>=9&&num<=10)
return -2;
}
int makeValid(int num)
{
if (num<0)
return 0;
else if (num>29)
return 29;
else
return num;
}
void main()
{
string position[31];
int pos_tortoise = 0;
int pos_hare = 0;
cout<<"BAHG!!!"<<endl<<"AND THEY'RE OFF!!!!"<<endl;
while(pos_tortoise<29&&pos_hare<29)
{
cout<<">";
for (int i=0;i<30;i++)
position[i]=" ";
position[30]="<";
srand( (unsigned)time(NULL) );
int num1 = getRand(10);
int num2 = getRand(10);
pos_tortoise += move_tortoise(num1);
pos_hare += move_hare(num2);
pos_tortoise = makeValid(pos_tortoise);
pos_hare = makeValid(pos_hare);
for (int j=0;j<31;j++)
{
if (j==pos_tortoise)
position[j]+="T.";
if (j==pos_hare)
position[j]+="H.";
if (j==pos_hare&&j==pos_tortoise)
position[j]+="OUCH.";
cout<<position[j];
}
cout<<endl;
system("pause");
}
if (pos_tortoise==29)
cout<<"Tortoise Wins!!!YAY!!!"<<endl;
else if (pos_hare==29)
cout<<"Hare Wins!!!Yuch!!!"<<endl;
else
cout<<"TIED"<<endl;
}
这篇关于简陋的龟兔赛跑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!