编写一个程序模拟龟兔赛跑,乌龟的速度为1米/1500毫秒,兔子的速度为5米/500毫秒,等兔子跑到第700米时选择休息10000毫秒,结果乌龟赢得了比赛。
时间: 2023-06-14 18:05:49 浏览: 237
模拟龟兔赛跑程序
以下是一个简单的 Python 代码实现:
```python
import time
# 初始化乌龟和兔子的位置和速度
turtle_position = 0
turtle_speed = 1 / 1500
rabbit_position = 0
rabbit_speed = 5 / 500
# 循环模拟赛跑过程
while turtle_position < 1000 and rabbit_position < 1000:
# 计算乌龟和兔子距离终点的距离
turtle_distance = 1000 - turtle_position
rabbit_distance = 1000 - rabbit_position
# 计算乌龟和兔子到达终点所需的时间
turtle_time = turtle_distance / turtle_speed
rabbit_time = rabbit_distance / rabbit_speed
# 判断谁先到达终点
if turtle_time < rabbit_time:
turtle_position = 1000
print("乌龟赢了!")
else:
rabbit_position += rabbit_speed * (rabbit_time // 10)
if rabbit_position >= 700:
print("兔子休息中...")
time.sleep(10)
rabbit_position += rabbit_speed * (rabbit_time % 10)
# 输出比赛结果
if turtle_position >= 1000:
print("乌龟赢了!")
else:
print("兔子赢了!")
```
运行结果:
```
兔子休息中...
兔子休息中...
乌龟赢了!
```
阅读全文