为什么这段代码会造成无限循环?我认为这应该是解决此类问题的合适方法。例如,如果价格为5美元,而您支付了5.47美元,该程序将打印:
Quarters: 1
Dimes: 2
Nickels: 0
Pennies: 2
但是,发生无限循环,我不确定为什么。有人知道原因吗?
price = round(float(input("Enter the price: ")), 2)
print price
paid = round(float(input("Enter the amount paid: ")), 2)
print paid
change = round(float(paid - price), 2)
print change
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while change > 0.00:
print change
if change >= .25:
change = change - .25
quarters += 1
continue
elif change >= .1:
change = change - .1
dimes += 1
continue
elif change >= .05:
change = change - .05
nickels += 1
elif change >= .01:
change = change - .01
pennies += 1
print "Quarters: " + str(quarters)
print "Dimes: " + str(dimes)
print "Nickels: " + str(nickels)
print "Pennies: " + str(pennies)
答案 0 :(得分:0)
我不建议处理循环,而是建议取消已收集的更改,并优先处理较大的硬币。
price = float(input("Enter the price: "))
paid = float(input("Enter the amount paid: "))
change = paid - price
if change < 0:
raise ValueError('Not enough paid')
quarters = change // 0.25
dimes = (change - (0.25 * quarters)) // 0.10
nickels = (change - (0.25 * quarters) - (0.10 * dimes)) // 0.05
pennies = 100 * (change - (0.25 * quarters) - (0.10 * dimes) - (0.05 * nickels))
print("Quarters: {:.0f}".format(quarters))
print("Dimes: {:.0f}".format(dimes))
print("Nickels: {:.0f}".format(nickels))
print("Pennies: {:.0f}".format(pennies))
答案 1 :(得分:0)
代码中存在一个小错误,该错误导致该程序仅在价格和付款金额互换时才能正常工作(例如,price = 2,paid = 1)。但这不是导致无限循环的问题。
您的代码会为例如以下参数:
可以从您自己的打印输出中看到无限循环的原因:
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
...
自change < 0.01
起,if子句不适用,因此永远不会离开循环。
您如何更稳健地解决问题?
这是草图
from math import floor
change = paid - price
quarters = int(floor(change / 0.25))
change -= quarters * 0.25
dimes = int(floor(change / 0.1))
change -= dimes * 0.1
nickels = int(floor(change / 0.05))
change -= nickels * 0.05
pennies = int(floor(change / 0.01))
change -= pennies * 0.01
remaining = change
print("Quarters:", quarters)
print("Dimes:", dimes)
print("Nickels:", nickels)
print("Pennies:", pennies)
我个人也将其简化为硬币类型的循环:
increments = {"quarter":0.25, "dimes": 0.1, "nickels": 0.05, "pennies": 0.01}
change_parts = {}
for inc_name, inc in increments.items():
amount = int(floor(change / inc))
print(inc_name, inc, amount)
change -= amount * inc
change_parts[inc_name] = amount
for inc_name, amount in change_parts.items():
print(inc_name + ":", amount)