我想在python 3
写一个贪婪的算法。
前提是将用户所欠的变更作为输入,并尽可能少地给他们提供硬币。
可用的硬币是:宿舍(0.25);硬币(0.1);镍(0.05);和便士(0.01)。
我的代码目前以无限循环结束,我不知道我做错了什么。
任何人都可以看到我在下面的代码出错了吗?
码:
validacion = False
pennies = 0.01
nickels = 0.05
dimes = 0.1
quarters = 0.25
coinCounter = 0
penniesCounter = 0
nickelsCounter = 0
dimesCounters = 0
quartersCounter = 0
cambio = False
while validacion is False:
changeOwed = float(input("Change owed: "))
if changeOwed > 0:
validacion = True
else:
validacion = False
while cambio is False:
if changeOwed > dimes and changeOwed <= quarters:
coinCounter += 1
quartersCounter += 1
changeOwed -= quarters
if changeOwed == 0.0:
cambio = True
elif changeOwed > nickels and changeOwed <= dimes:
coinCounter += 1
nickelsCounter += 1
changeOwed -= nickels
if changeOwed == 0.0:
cambio = True
elif changeOwed > pennies and changeOwed <= nickels:
coinCounter += 1
dimesCounters += 1
changeOwed -= dimes
if changeOwed == 0.0:
cambio = True
else:
coinCounter += 1
penniesCounter += 1
changeOwed -= pennies
if changeOwed == 0.0:
cambio = True
print(coinCounter)
在苛刻的ossifrage的建议之后,将你的任务改为:
pennies = 1
nickels = 5
等等。然后使用整数美分而不是IEEE-754二进制FP美元来测试您的代码。
让我们说你欠0.46的变化。所以你应该给:1季度,2角钱和1分钱:
>>> 0.46 - 0.25 - 0.1 - 0.1 -0.01
8.673617379884035e-18
正如你所看到的那样,它不是0.计算机以二进制形式处理,而不是所有小数部分都很好地转换为二进简短的解决方案是将所有乘以100并处理整数:
>>> 46 - 25 - 10 - 10 -1
0
对于输入,您可以像这样乘以:
changeOwed = int(round(changeOwed * 100)) # 0.58*100 == 57.99999999
接下来的问题是,如果你的欠款少于四分之一,你可以给出一个季度。它应该是:
if changeOwed >= quarters:
# the quarter process
elif changeOwed >= dimes:
# the dime process
#etc...
而不是做while cambio == False
,这样做更有意义:
while changeOwed >= pennies: # the smallest coin you can give out
祝好运!