2013-06-06 74 views
0

我有一个while循环,它返回爬起山坡所需的'rush'数量。 山的大小是'坡高',高度上升是'rush_height_gain'减去'back_sliding'。while循环(Python)

下面的代码适用于:

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) 
+0

应该怎么办?大多数人不想猜测。 – squiguy

+0

您可以添加实际和预期的输出吗? – jpmc26

+0

http://pythonfiddle.com/rushes-quiz-work/ – perreal

回答

4

如果我理解正确的问题,我想你要寻找的是:

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在他对原帖的评论中的链接中指出的那样,如果你滑下的次数超过了第一次滑出的时间,并且没有完全融化,那么你将会遇到问题。在这种情况下您可能想要抛出异常。

+0

非常感谢! – user2101517

+0

@ user2101517没有问题。 Python很有趣! – Andbdrew

0

我相信这个问题是这样的语句:

 if current_height == slope_height: 
      return rushes 

back_sliding0,然后在第十次迭代,current_height去从90100。然后该检查返回true,并在9递增之前返回。

0
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