20111109练习2:模拟龟兔赛跑

从70个方格的第一个格子起跑,每个格子表示跑道上的可能位置

显示乌龟的位置 T ,兔子的位置 H ,和撞到一起的位置 !,其他位置输出 —。

结束后,测试哪个动物超过70格就赢。

 

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int tortoise(int, int);
int hare(int, int);

int main()
{
 char square[71] = {0};           //创立一个数组,作为标记龟兔的状态
 int countTortoise = 1, countHare = 1;
 int pass = 1;
 srand(time(0));
 while (/*countTortoise != 70 && countHare != 70 &&*/ pass != 70)  //乌龟和兔子有一个赢或者时间pass结束 则循环结束
 {
  int nTortoise = 1 + rand() % 10 ;
  countTortoise = tortoise(nTortoise, countTortoise);
  square[countTortoise] = 'a';        //在乌龟走的位置上标记为a

  int nHare = 1 + rand() % 10;
  countHare = hare(nHare, countHare);
  if(countHare == countTortoise)
   square[countHare] = 'c';        //走到一起了 就标记为c
  else
   square[countHare] = 'b';        //兔子位置上标记为b

  pass ++;
 }

 for (int i = 1; i <= 70; i++)
 {
  switch(square[i])
  {
  case 0:
   cout << "-";
   break;
  case 'a':
   cout << "T";
   break;
  case 'b':
   cout << "H";
   break;
  case 'c':
   cout << "!";
   break;
  default:
   break;

  }
  

 }
 cout << endl;
 if(countTortoise >= 70)
  cout << "the tortoise win!"<< endl;
 else if (countHare >= 70)
  cout << "the hare wins" << endl;
 else
  cout << "it's a tie" << endl;

 return 0;
}

int tortoise(int n, int count)  //乌龟50%概率前进3格,20%后退6格, 30%前进一格
{
 if(n >=1 && n <= 5)
  count += 3;
 else if(n >= 8 && n <= 10)
  count += 1;
 else
  count -= 6;
 if(count < 1)
  count = 1;
 return count;
}

int hare(int n, int count)//兔子20%不动,20%前进9,10%后退12,30%前进1,20%后退2
{
 if(n == 3 || n == 4)
  count += 9;
 else if(n==5)
  count -= 12;
 else if(n >= 6 && n <= 8)
  count += 1;
 else if(n == 9 && n == 10)
  count -= 2;

 if(count < 1)
  count = 1;
 return count;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值