2017-10-10 112 views
2

我正在製作一個程序,在一個地下室電話計劃中,用戶有400分鐘,他們可以使用20美元一個月。然後,如果用戶在一個月內使用超過400分鐘,他們在計劃的400分鐘以外每分鐘收取5美分。向用戶詢問本月使用的分鐘數,然後計算其賬單。確保你檢查是否輸入了一個負數(然後你應該輸出「你輸入了一個負數」)。Python程序給我錯誤的答案

我的代碼:

def main(): 
    # the bill will always be at least 20 
    res = 20 
    # again is a sentinel 
    # we want the user to at least try the program once 
    again = True 
    while again: 
     minutes = int(input("How many minutes did you use this month? ")) 
     # error correction loop 
     # in the case they enter negative minutes 
     while minutes < 0: 
      print("You entered a negative number. Try again.") 
      # you must cast to an int 
      # with int() 
      minutes = int(input("How many minutes did you use this month? ")) 
     # get the remainder 
     remainder = minutes - 400 
     # apply five cent charge 
     if remainder > 0: 
      res += remainder * 0.05 
     print("Your monthly bill is: ","$",res) 

     det = input("Would you like to try again? Y/N: ") 
     again = (det == "Y")  
main() 

如果我在600型我得到正確的答案是$ 30,當它要求再次輸入時,我輸入Y代表是的,然後輸入500以下的任何值,然後我得到35美元的答案,這是沒有意義的。再次,如果你鍵入y並輸入更低的價格,價格就會上漲。看起來分鐘下跌時價格上漲,但如果分鐘上漲,價格應該上漲。

我在做什麼錯。並感謝您的時間。

回答

2

您需要將res移動到循環內部,以便重置。就像這樣:

#!/usr/bin/env python3.6 


def main(): 
    # again is a sentinel 
    # we want the user to at least try the program once 
    again = True 
    while again: 
     res = 20 # Reset this variable 
     minutes = int(input("How many minutes did you use this month? ")) 
     # error correction loop 
     # in the case they enter negative minutes 
     while minutes < 0: 
      print("You entered a negative number. Try again.") 
      # you must cast to an int 
      # with int() 
      minutes = int(input("How many minutes did you use this month? ")) 
     # get the remainder 
     remainder = minutes - 400 
     # apply five cent charge 
     if remainder > 0: 
      res += remainder * 0.05 
     print("Your monthly bill is: ", "$", res) 

     det = input("Would you like to try again? Y/N: ") 
     again = (det == "Y") 


main() 

你有它的方式,res只是不停地永遠遞增,從不被重置爲20

+0

哦,那個男人我怎麼沒有抓住那個......謝謝!現在完美運作。 – Matticus

1

您不會在每次嘗試之間重置res,因此每次循環都將其添加到。看起來你希望每個循環都相互獨立,所以這種行爲是無意的。

右下while again:,重置res被重新分配給20你可能甚至不需要申報擺在首位res外循環,因爲它看起來像它的環路的範圍之內只用過。

+0

謝謝你的解釋 – Matticus

+0

@Matticus Np個。您應該接受我們的答案,將您的問題標記爲已解決。 – Carcigenicate

相關問題