2 回答
TA贡献1765条经验 获得超5个赞
while由于浮点数的内部表示引起的与浮点值相关的一些舍入错误,您的程序正在运行无限循环。因此,要修复这些错误,我们可以使用round()函数在每次循环迭代owed结束时对值进行四舍五入:while
elif owed % 0.25 != 0:
while owed > 0:
if (owed - 0.25) >= 0:
coins += 1
owed -= 0.25
elif (owed - 0.10) >= 0:
coins += 1
owed -= 0.10
elif (owed - 0.05) >= 0:
coins += 1
owed -= 0.05
elif (owed - 0.01) >= 0:
coins += 1
owed -= 0.01
owed = round(owed, 3) # In this line, we roundoff the value of owed
print(int(coins))
exit()
这很好用。
希望这可以帮助 :)
TA贡献1829条经验 获得超4个赞
while由于浮点错误,您的程序卡在循环中。尝试在while循环中添加以下代码,您会看到 whileowed确实变得无限小,它永远不会变为零:
...
while owed > 0:
print(owed)
...
输出:
...
8.326672684688674e-17
8.326672684688674e-17
8.326672684688674e-17
8.326672684688674e-17
...
考虑将输入乘以100然后将其作为整数处理:
owed = int(float(input("How much change is owed? $")) * 100)
quarters = int(owed / 25)
dimes = int((owed - quarters * 25) / 10)
nickels = int((owed - quarters * 25 - dimes * 10) / 5)
cents = int((owed - quarters * 25 - dimes * 10 - nickels * 5))
coins = (quarters + dimes + nickels + cents)
print('Quarters (${}): {}'.format(quarters*0.25, quarters))
print('Dimes (${}): {}'.format(dimes*0.1, dimes))
print('Nickels (${}): {}'.format(nickels*0.05, nickels))
print('Cents (${}): {}'.format(cents, cents))
print('Coins:', coins)
或者,如果您想坚持使用贪心算法:
owed = int(float(input("How much change is owed? $")) * 100)
while owed > 0:
if (owed - 25) >= 0:
coins += 1
owed -= 25
elif (owed - 10) >= 0:
coins += 1
owed -= 10
elif (owed - 5) >= 0:
coins += 1
owed -= 5
elif (owed - 1) >= 0:
coins += 1
owed -= 1
coins = (quarters + dimes + nickels + cents)
print('Quarters (${}): {}'.format(quarters*0.25, quarters))
print('Dimes (${}): {}'.format(dimes*0.1, dimes))
print('Nickels (${}): {}'.format(nickels*0.05, nickels))
print('Cents (${}): {}'.format(cents, cents))
print('Coins:', coins)
输出
>>> How much change is owed? $1.42
Quarters ($1.25): 5
Dimes ($0.1): 1
Nickels ($0.05): 1
Cents ($2): 2
Coins: 9
有关浮点限制的更多信息,请查看以下内容:https ://docs.python.org/3.8/tutorial/floatingpoint.html
添加回答
举报