基于python的硬币面值识别_列出给定数量的python需要什么硬币

本文讨论了一个Python函数,该函数旨在根据给定金额找出英国硬币的数量。作者发现函数在处理0.05和0.01面值的硬币时出现问题。他们已经提供了函数代码并展示了预期输出与实际输出的对比。问题可能与处理小数点后两位的数值有关。
摘要由CSDN通过智能技术生成

我需要编写一个函数,以列表格式打印给定金额所需的英国硬币数量(即列表中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位)。你知道怎么解决吗?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值