我是第一年的编程学生,我在尝试让我的代码正确循环时遇到了麻烦,我想了解如何让它按照需要运行。我正在运行一个程序,它将使用每个硬币的预设库存计算更改,价格和付款将由用户输入,更改将通过库存中剩余的硬币数量返回。现在我在努力让计划退回资金不足的时候遇到了困难。而且没有变化'打印语句,试图让它从四分之一到一角硬币到镍币和硬币正确地循环,我不确定我可能做错了什么。
quarters = 10
dimes = 10
nickels = 10
pennies = 10
stock = quarters, dimes, nickels, pennies
print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
payment_int = int(input("Input dollars paid (int):"))
change_sum = float(payment_int) - in_str
#in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
change_sum = change_sum - 0.25
quarters -= 1
print(quarters, change_sum)
elif dimes > 0 and 0.25 > change_sum >= 0.10:
change_sum = change_sum - 0.1
dimes -= 1
print(dimes, change_sum)
elif nickels > 0 and 0.1 > change_sum >= 0.05:
change_sum = change_sum - 0.05
nickels -= 1
print(nickels, change_sum)
elif pennies > 0 and 0.05 > change_sum >= 0.01:
change_sum = change_sum -0.01
pennies -=1
print(pennies, change_sum)
else:
if change_sum == 0.0:
break
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
print(change_sum)
答案 0 :(得分:0)
如果资金不足,则change_sum
为<0
且while
循环永不运行。这就是为什么你没有得到资金不足的原因&#34;信息。您应首先检查充足性,然后开始循环:
只需更改此部分:
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
到此:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
while change_sum >= 0:
if quarters > 0 and change_sum >= 0.25: