程序计算硬币的存量变化。然后,它要求购买物品的价格。如果输入了价格,它将提示您输入美元并打印硬币找零。
我尝试了以下代码:
quarters = 10
dimes = 10
nickels = 10
pennies = 10
quarters_spent = 0
dimes_spent = 0
nickels_spent = 0
pennies_spent = 0
print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))
in_str = input("Enter the purchase price (xx.xx) or 'q' to quit: ")
while in_str.lower() != 'q':
dollar_str, cents_str = in_str.split(".")
in_int = int(float(in_str)*100)
if in_int < 0:
print("Error: purchase price must be non-negative.")
in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")
if in_int > 0:
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment)*100)
if payment_int < in_int:
print("Error: print again.")
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment)*100)
change = payment_int - in_int
if change == 0:
print("No change.")
while change >= 25 and quarters > 0:
change -= 25
quarters_spent += 1
quarters -= 1
while change >= 10 and dimes > 0:
change -= 10
dimes_spent += 1
dimes -= 1
while change >= 5 and nickels > 0:
change -= 5
nickels_spent += 1
nickels -= 1
while change >= 1 and pennies > 0:
change -= 1
pennies_spent += 1
pennies -= 1
if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
print("Error: ran out of coins.")
quit()
print("\nCollect Payment Below:")
if quarters > 0:
print(quarters_spent, "quarters")
if dimes > 0:
print(dimes_spent, "dimes")
if nickels > 0:
print(nickels_spent, "nickels")
if pennies > 0:
print(pennies_spent, "pennies")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))
in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")
输入: 1.5 2 q 我期望输出: 8 q,10 d,10 n和10 p
实际结果: 该程序无法运行,要求输入“输入购买价格(xx.xx)或'q'退出:”,然后什么也没有发生。询问短语后,该程序根本无法运行。
答案 0 :(得分:1)
如果输入不是Q
或q
,则循环将是无限的:
while in_str.lower() != 'q':
dollar_str, cents_str = in_str.split(".")
修复:还允许循环内其他可接受的输入或重新请求输入。