【发布时间】:2018-09-27 11:09:11
【问题描述】:
我需要创建一个脚本,要求用户输入 $ 金额,然后输出最小数量的硬币以使用硬币、硬币、镍和便士创建该 $ 金额。
mTotal = (float(input("Enter the amount you are owed in $:")))
numCoins = 0
while (mTotal != 0):
if ((mTotal - 0.25) >= 0):
mTotal-=0.25
numCoins += 1
elif ((mTotal - 0.10)>= 0):
mTotal-=0.10
numCoins += 1
elif ((mTotal - 0.05)>= 0):
mTotal-=0.05
numCoins += 1
elif ((mTotal - 0.01)>= 0):
mTotal-=0.01
numCoins += 1
print("The minimum number of coins the cashier can return is:", numCoins)
由于某种原因,它只有在我输入 0.01、0.05、0.10 或 0.25 的精确倍数时才有效,否则 while 循环将永远持续下去。
【问题讨论】:
-
你试过了吗-while(mTotal > 0):
-
这是你应该做的。在
while loop开头,加上print(mTotal),运行程序看看为什么不停止 -
我在 while 循环的开头添加了 print(mTotal),它一直在打印一个非常小的数字。像 5.03e-17 这样的东西。为什么会这样??
-
您不应该使用浮点值来赚钱。你应该使用整数美分。
-
请阅读stackoverflow.com/questions/19473770/…获取解释和解决方案。
标签: python