【发布时间】:2017-08-18 18:22:20
【问题描述】:
当一个人跑上斜坡时,他会冲到耗尽能量然后停下来休息一下,该函数返回他冲上斜坡直到他到达顶部的次数。每次他再次冲上去,他都会损失 5%。但是,当我运行这个程序时,它需要很长时间并且不会返回任何东西。它应该返回 19。
def num_rushes(slope_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
while current_height < slope_height:
current_height += rush_height_gain
if current_height < slope_height:
current_height -= back_sliding
rushes += 1
rush_height_gain = rush_height_gain * 0.95
return rushes
ans = num_rushes(100, 15, 7)
print(ans)
【问题讨论】:
-
我建议在循环中添加一些打印语句,以查看每次迭代后值的变化情况,看看出了什么问题。你没有对
back_sliding变量做任何事情,所以也许你忘了做部分问题。 -
您确定这是您正在运行的代码吗?我复制并粘贴它,几乎立即得到 8 作为输出。
-
当我在 Python 3.5.3 中运行它时,它会很快结束并打印出
8。当然,我在运行之前修复了缩进。你真的在每一行前面都有这些空格吗? -
我添加了 back_sliding 位。这只是减去了它们停止后向后滑动的量。我把它拿出来是因为我认为这不是问题所在,并且希望问题尽可能简单。但是现在我更困惑了。
-
随着登山者减速,它的净速度实际上可能变为负数 (
rush_height_gain - back_sliding < 0)。你将如何解释这一点?
标签: python function while-loop