2017-10-10 113 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

相关问题