2013-06-06 231 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