我需要编写一个函数,以列表格式打印给定金额所需的英国硬币数量(即列表中8个值,分别为2英镑、1英镑、0.50英镑、0.20英镑、0.10英镑、0.05英镑、0.02英镑和0.01英镑)。在
到目前为止,我写了以下内容:def pay_with_coins( amount ):
coins_list = [0, 0, 0, 0, 0, 0, 0, 0]
if amount == 0:
return(coins_list)
else:
while amount > 2.00:
coins_list[0] = (coins_list[0] + 1)
amount = amount - 2.00
while amount >= 1.00 and amount < 2.00:
coins_list[1] = (coins_list[1] + 1)
amount = amount - 1.00
while amount >= 0.50 and amount < 1.00:
coins_list[2] = (coins_list[2] + 1)
amount = amount - 0.50
while amount >= 0.20 and amount < 0.50:
coins_list[3] = (coins_list[3] + 1)
amount = amount - 0.20
while amount >= 0.10 and amount < 0.20:
coins_list[4] = (coins_list[4] + 1)
amount = amount - 0.10
while amount >= 0.05 and amount < 0.10:
coins_list[5] = (coins_list[5] + 1)
amount = amount - 0.05
while amount >= 0.02 and amount < 0.05:
coins_list[6] = (coins_list[6] + 1)
amount = amount - 0.02
while amount >= 0.01 and amount < 0.05:
coins_list[7] = (coins_list[7] + 1)
amount = amount - 0.01
return(coins_list)
我通过传递以下内容来测试函数:
^{pr2}$
这就是我应该得到的:[0,0,0,0,0,1,1,1]
[4,0,0,0,0,0,1,0]
[0,1,1,1,0,0,2,0]
[500,1,0,0,0,0,0,0]
我得到的是:[0, 0, 0, 0, 0, 1, 1, 0]
[4, 0, 0, 0, 0, 0, 0, 1]
[0, 1, 1, 1, 0, 0, 1, 1]
[500, 1, 0, 0, 0, 0, 0, 0]
正如您所看到的,列表中的最后两个值似乎出现了问题,我不太确定问题出在哪里。在
我有一种感觉,最后两个值弄乱了,因为它们是0.05和0.01(小数点后2位)。你知道怎么解决吗?在