While循环(Python)

我有一个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)


富国沪深
浏览 203回答 4
4回答

慕斯709654

如果我正确地理解了这个问题,那么我认为您正在寻找的是:def num_rushes(slope_height, rush_height_gain, back_sliding):&nbsp; &nbsp; if rush_height_gain < slope_height and rush_height_gain - back_sliding < 1:&nbsp; &nbsp; &nbsp; &nbsp; raise Exception("this is not going to work very well")&nbsp; &nbsp; current_height = rushes = 0&nbsp; &nbsp; while current_height < slope_height:&nbsp; &nbsp; &nbsp; &nbsp; rushes += 1&nbsp; &nbsp; &nbsp; &nbsp; current_height += rush_height_gain&nbsp; &nbsp; &nbsp; &nbsp; if current_height >= slope_height:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; current_height -= back_sliding&nbsp; &nbsp; return rushes每次上坡“奔波”后,您都要检查是否已经到达山顶。如果是这样,那么您就完成了;如果没有,那么请向下滑动一下再走一次!正如@perreal在他对原始帖子的评论中的链接中所指出的那样,如果您滑倒的次数多于滑倒的次数,并且第一次没有完全站起来,那么您将会遇到问题。在这些情况下,您可能想抛出一个异常。

犯罪嫌疑人X

我相信问题是这样的:&nbsp; &nbsp; &nbsp; &nbsp; if current_height == slope_height:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rushes如果back_sliding是0,那么在第十次迭代,current_height从去90到100。然后,支票返回true,并9在递增之前返回。

呼如林

def num_rushes(slope_height, rush_height_gain, back_sliding):&nbsp; &nbsp; current_height = 0&nbsp; &nbsp; rushes = 0&nbsp; &nbsp; while current_height < slope_height:&nbsp; &nbsp; &nbsp; &nbsp; current_height += rush_height_gain&nbsp; &nbsp; &nbsp; &nbsp; rushes += 1&nbsp; &nbsp; &nbsp; &nbsp; if current_height < slope_height:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current_height -= back_sliding&nbsp; &nbsp; return rushes
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python