#include<iostream>
#include<cstdlib>
#include<time.h>
#include<ctime>
#include<iomanip>
using namespace std;
const int End=70; //constant fixed integer for the entire game.
void MoveTurtoise (int *);
void MoveHare (int *);
void PrintPosition (int *, int*);
int main()
{
int Tortoise = 1;
int Hare = 1;
int Time = 0;
srand(time(0));
cout<<"BANG!!!!!\n"
<<"AND THEY'RE OFF !!!!!\n";
while(Tortoise != End && Hare != End)
{
srand(time(0));
MoveTurtoise (&Tortoise);
MoveHare (&Hare);
PrintPosition (&Tortoise,&Hare);
Time++;
}
if (Tortoise==Hare)
cout<<"It's a tie."<<endl;
else if (Tortoise>Hare)
cout<<"Tortoise wins."<<endl;
else if (Hare>Tortoise)
cout<<"Hare wins."<<endl;
system("PAUSE");
return 0;
}
void MoveTurtoise (int *Tortoise)
{
srand(time(0));
int p = 1+ rand()%10; // 1 <= i <= 10
if (1<=p && p<=5) //Fast plod
Tortoise+=3; //3 squares right
else if (p>=6 && p<=7) //Slip
Tortoise-=6;//6 squares left
else //Slow plod
++Tortoise; //1 square right
if (*Tortoise<1)
*Tortoise=1;
}
void MoveHare (int *Hare)
{
srand(time(0));
int p = 1+ rand()%10; // 1 <= p <= 10
if (1<= p && p<=2); //Sleep
//No move
else if (p>=3 && p<=4) //Big hop
Hare+=9;//9 squares right
else if (p==5) //Big Slip
Hare-=12;// 12 squares left
else if (p>=6 && p<=8) // Small hop
++Hare;// 1 square right
else if (p>=9 && p<=10)// Small Slip
Hare-=2; // 2 squares left
if (*Hare<1)
*Hare=1;
}
void PrintPosition (int *Tortoise, int *Hare)
{
if (Tortoise==Hare)
cout<<"OUCH!!!"<<endl;
else if (Tortoise<Hare)
{
cout<<setw(*Tortoise)<<"T"<<endl;
cout<<setw(Hare-Tortoise)<<"H"<<endl;
}
else if (Hare<Tortoise)
{
cout<<setw(Tortoise-Hare)<<"T"<<endl;
cout<<setw(*Hare)<<"H"<<endl;
}
}
大家好。我只是用C++编写了一个用于Tortoise和Hare模拟游戏的代码。我有一个问题发现是什么导致我的程序“不”终止。它一直在继续,并取得了相同的结果。我假设有一个循环错误和错误的使用srand()..但我仍然没有线索...乌龟和野兔模拟终止问题
你试过调试过吗? “乌龟”和“野兔”是否增加?他们是否达到70?超过70? – 2014-09-23 16:47:34
我调试,我看到的是T和H重复相同的结果。 – user3543568 2014-09-23 16:50:03
我不认为你需要在每个函数中使用'srand'。只需在'main'中使用它,并在循环中删除'srand',因为在它之前已经有一个。 – 2014-09-23 17:00:13