我有一个while循环,它返回爬上一座山所需的“冲刺”次数。小山的大小是“坡度高度”,向上的高度是“rush_height_gain”减去“back_sliding”。
下面的代码适用于:
ans = num_rushes(15, 10, 5)
print(ans)哪个打印1
和
ans = num_rushes(100, 15,7)
print(ans)哪个打印2
和
ans = num_rushes(10, 10, 9)
print(ans)其中打印了12
,但返回错误的答案。
ans = num_rushes(100, 10, 0)
print(ans)它应该打印10,而不是打印9
我不知道为什么会这样,任何帮助都将不胜感激
def num_rushes(slope_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
while current_height < slope_height:
if rush_height_gain == slope_height:
rushes+=1
return rushes
elif current_height < slope_height:
if current_height == slope_height:
return rushes
else:
a = rush_height_gain - back_sliding
current_height += a
if current_height == slope_height:
return rushes
elif current_height > slope_height:
return rushes
else:
rushes+=1
return (rushes)发布于 2013-06-06 09:53:59
如果我对这个问题的理解正确的话,我认为你想要的是:
def num_rushes(slope_height, rush_height_gain, back_sliding):
if rush_height_gain < slope_height and rush_height_gain - back_sliding < 1:
raise Exception("this is not going to work very well")
current_height = rushes = 0
while current_height < slope_height:
rushes += 1
current_height += rush_height_gain
if current_height >= slope_height:
break
current_height -= back_sliding
return rushes每次上坡“冲刺”后,你都会检查自己是否已经到达顶峰。如果是这样,你就完成了,如果不是,你滑下来一点,然后再滑一遍!正如@perreal在他的原始帖子的评论链接中指出的那样,如果你滑下来的次数超过了你滑上去的次数,并且第一次没有站起来,你就会有问题。在这些情况下,您可能需要抛出异常。
发布于 2013-06-06 09:55:21
我认为问题出在这句话上:
if current_height == slope_height:
return rushes当back_sliding为0时,在第十次迭代中,current_height从90转到100。然后检查返回true,并且在递增之前返回9。
发布于 2013-06-06 10:03:06
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
rushes += 1
if current_height < slope_height:
current_height -= back_sliding
return rusheshttps://stackoverflow.com/questions/16952464
复制相似问题