21xrx.com
2025-04-01 19:59:40 Tuesday
文章检索 我的文章 写文章
C++编写的龟兔赛跑程序代码
2023-07-01 14:16:08 深夜i     18     0
C++ 编写 龟兔赛跑 程序代码 比赛模拟

龟兔赛跑是一个经典的童话故事,它也是计算机编程机器人竞赛中的一个著名问题。在这个问题中,需要模拟龟兔赛跑,即通过编写程序来模拟龟和兔之间的比赛,以确定谁最终会赢得比赛。

最常用的编程语言之一是C++。以下是一个使用C++编写的龟兔赛跑程序代码。在这个程序中,我们使用了类和继承的概念来定义龟和兔的属性和行为。我们还使用了随机数生成器来确定每个动物在每个时间步骤中走的距离。

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class Animal
{
public:
  Animal();
  virtual ~Animal();
  virtual void run() = 0;
  virtual void get_step() = 0;
  virtual bool winner() = 0;
  int location;
  int steps;
};
Animal::Animal()
  location = 0;
  steps = 0;
Animal::~Animal()
class Turtle : public Animal
{
public:
  Turtle();
  ~Turtle();
  void run();
  void get_step();
  bool winner();
};
Turtle::Turtle()
Turtle::~Turtle()
void Turtle::run()
  cout << "I am a turtle and I am running!" << endl;
void Turtle::get_step()
{
  int boundary = 6;
  int random = 1 + rand() % boundary;
  if (random <= 2)
  {
    steps += 6;
  }
  if (random >= 3 && random <= 4)
  
    steps -= 2;
  
  if (random >= 5 && random <= 6)
  {
    steps += 1;
  }
  location += steps;
}
bool Turtle::winner()
{
  if (location >= 100)
  
    return true;
  
  else
  
    return false;
  
}
class Rabbit : public Animal
{
public:
  Rabbit();
  ~Rabbit();
  void run();
  void get_step();
  bool winner();
};
Rabbit::Rabbit()
Rabbit::~Rabbit()
void Rabbit::run()
  cout << "I am a rabbit and I am running!" << endl;
void Rabbit::get_step()
{
  int boundary = 10;
  int random = 1 + rand() % boundary;
  if (random <= 2)
  {
    steps += 0;
  }
  if (random >= 3 && random <= 4)
  {
    steps += 9;
  }
  if (random >= 5 && random <= 5)
  
    steps -= 12;
  
  if (random >= 6 && random <= 8)
  {
    steps += 1;
  }
  if (random >= 9 && random <= 10)
  
    steps -= 2;
  
  location += steps;
}
bool Rabbit::winner()
{
  if (location >= 100)
  
    return true;
  
  else
  
    return false;
  
}
void racing(Animal* animal)
{
  animal->run();
  animal->get_step();
  if (animal->winner())
  {
    cout << "The winner is: " << typeid(*animal).name() << endl;
    exit(0);
  }
}
int main()
{
  srand(static_cast<unsigned int>(time(nullptr)));
  Turtle turtle;
  Rabbit rabbit;
  while (true)
  {
    racing(&rabbit);
    racing(&turtle);
  }
  return 0;
}

在这个程序中,我们首先定义了两个基类:Animal和其子类Turtle和Rabbit。Animal是一个抽象类,因为它的run()、get_step()和winner()方法都是虚函数。Turtle和Rabbit都继承自Animal,并且根据其各自的特征重写了这些方法。

在程序的main()函数中,我们初始化了一个乱数生成器,并在一个while循环中不断调用racing()函数,直到某个动物达到了100的位置。racing()函数负责进行龟兔赛跑的模拟,内部首先调用动物对象的run()方法来输出类别名称,并生成随机步数,然后调用get_step()方法来更新动物的位置。如果动物对象的winner()方法返回true,则表示该动物已经到达终点,并输出胜利者类别名称。

通过这个C++程序,我们成功地实现了龟兔赛跑的模型,并演示了如何使用OOP编程技巧来实现这个问题。

  
  

评论区

请求出错了