def pay(cost, selection,):
deposit = 0
deficit = cost - deposit
change = deposit - cost
print("That item will cost you $",cost,".")
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n"))
if deposit < cost:
while deficit >= cost:
deficit -= float(input("Please enter an additional $" + str(deficit) + "."))
if deficit > cost:
print("Your change is $",change,".")
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
returnyn = input("Would you like to make another purchase? Answer with a y or n\n")
if returnyn == "Y" or returnyn == "y":
return
if deposit == cost:
print("Thank you for purchasing item#",selection,".")
returnyn = input("Would you like to make another purchase? Answer with a y or n\n")
if returnyn == "Y" or returnyn == "y":
return
if deposit > cost:
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
returnyn = input("Would you like to make another purchase? Answer with a y or n\n")
if returnyn == "Y" or returnyn == "y":
return
else:
exit()
def main():
cost = 0
selection = 0
loopCount = 0
flag = 0
print("--- Welcome to the HOWE CO. VENDOTRON ---\n --- Please make a selection below ---\n")
while loopCount < 3 or flag == 0:
loopCount +=1
if loopCount == 1:
print("You have three transactions left.")
if loopCount == 2:
print("You have two transactions left.")
if loopCount == 3:
print("You have one transaction left.")
if loopCount == 4:
print(("Thank you for your business!"))
break
print ("Item#\tCost")
print("1)\t\t$1.75\n2)\t\t$.75\n3)\t\t$.90\n4)\t\t$.75\n5)\t\t$1.25\n6)\t\t$.75\n7)\t\tExit transaction\n-----\n")
selection = int(input("Please enter the item number:\n"))
if selection > 6 or selection < 1:
print("Invalid input.")
if selection == 1:
cost = 1.75
x = pay(cost,selection,)
if selection == 2:
cost = 0.75
x = pay(cost,selection,)
if selection == 3:
cost = 0.90
x = pay(cost,selection,)
if selection == 4:
cost = 0.75
x = pay(cost,selection,)
if selection == 5:
cost = 1.25
x = pay(cost,selection,)
if selection == 6:
cost = 0.75
x = pay(cost,selection,)
if selection == 7:
print(("Thank you for your business!"))
break
main()
你好。我在做一个自动售货机程序。传递到“pay”函数的变量的行为不稳定。例如,如果您输入的金额不足,并且它请求额外的输入,那么它请求的是项目的成本,而不是成本保证金(赤字)。它也不能正确地计算更改。例如,如果我选择项目1(即1.75)并支付2美元,而不是给我正确的找零金额,它会给我以下信息:
“感谢您购买第1项。找您的零钱是-1.75美元。”
我假设支付功能有问题,但我不知道是什么。我已经花了好几个小时研究这个问题了。一定有不正确的数额之间的联系,额外的钱需要的项目和不正确的数额的变化给予了回报。环路有问题吗?缩进?请原谅,如果这是一件非常简单的事情——我只做了几个月的编程,还有很多东西要学
你的计算顺序不对。在以下代码中:
deficit
最初总是等于cost
,因为您根据用户输入更改了deposit
,但不重新计算deficit
(它是从初始化为0
的deposit
计算出来的),所以deficit
仍然等于cost
,而且由于deposit
从未使用过,它将“吃掉”最初不足的存款,而不会记入您的贷方。您需要在读入deposit
之后而不是之前计算deficit
。您还需要检查赤字是否是> 0
,而不是>= cost
,因为您试图消除缺口,而不是使缺口小于成本代码可能会使用许多其他清理,但这正是导致所描述的问题的原因
相关问题 更多 >
编程相关推荐