首页 > 解决方案 > 寻找数字的变化

问题描述

我是初学者,我得到了一个项目。我现在写下的内容适用于除我需要 83 之外的每个数字,它说我不需要镍。我尝试进行不同的操作,但这会使数学与其他数字混淆。如果你能帮忙那就太好了。

total = int(input("Enter change [0...99]: "))
half = total // 50
quarter = total % 50 // 25
dimes = total % 25 // 10
nickels = total % 10 // 5
pennies = total % 5 // 1

print(half, "half (ves)")
print(quarter, "Quarter (s)")
print(dimes, "Dime (s)")
print(nickels, "Nickel (s)")
print(pennies, "penny (s)")

标签: python

解决方案


您应该total在每枚硬币后更新:

half = total // 50
total = total % 50
# ...

这是因为并非所有代币都是前面所有代币的分隔符。例如25,从一个数量中移除会改变它的可分性10,因此total % 10remainder_after_dimes(如果您有奇数个季度)的数量不同。

这可以在一个步骤中完成,使用divmod

half, total = divmod(total, 50)
quarter, total = divmod(total, 25)
dimes, total = divmod(total, 10)
nickels, total = divmod(total, 5)
pennies, total = divmod(total, 1)

推荐阅读