首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >While循环(Python)

While循环(Python)
EN

Stack Overflow用户
提问于 2013-06-06 09:46:38
回答 3查看 804关注 0票数 0

我有一个while循环,它返回爬上一座山所需的“冲刺”次数。小山的大小是“坡度高度”,向上的高度是“rush_height_gain”减去“back_sliding”。

下面的代码适用于:

代码语言:javascript
复制
ans = num_rushes(15, 10, 5)
print(ans)

哪个打印1

代码语言:javascript
复制
ans = num_rushes(100, 15,7)
print(ans)

哪个打印2

代码语言:javascript
复制
ans = num_rushes(10, 10, 9)
print(ans)

其中打印了12

,但返回错误的答案。

代码语言:javascript
复制
ans = num_rushes(100, 10, 0)
print(ans)

它应该打印10,而不是打印9

我不知道为什么会这样,任何帮助都将不胜感激

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-06 09:53:59

如果我对这个问题的理解正确的话,我认为你想要的是:

代码语言:javascript
复制
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在他的原始帖子的评论链接中指出的那样,如果你滑下来的次数超过了你滑上去的次数,并且第一次没有站起来,你就会有问题。在这些情况下,您可能需要抛出异常。

票数 4
EN

Stack Overflow用户

发布于 2013-06-06 09:55:21

我认为问题出在这句话上:

代码语言:javascript
复制
        if current_height == slope_height:
            return rushes

back_sliding0时,在第十次迭代中,current_height90转到100。然后检查返回true,并且在递增之前返回9

票数 0
EN

Stack Overflow用户

发布于 2013-06-06 10:03:06

代码语言:javascript
复制
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 rushes
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16952464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档