如何修复我的模数过滤器以正确计算每张账单的金额?

How to fix my modulus filter to correctly calculate the amount of each bill?

我主要在 Python 中编写代码,我一直在研究这个假 ATM 机。您可以输入您想要提取的金额,它会记录在 Transaction History.txt 上并计算达到您的金额所需的每张账单金额。

一切都按预期工作,除了模数过滤器...

这是我创建的模数过滤器,用于计算达到您的价值所需的每张账单金额:

import math
import time

amount = input("Input: ")
print("Withdrawing €%s..." % amount)
time.sleep(0.5)
amount = float(amount)

b500 = math.floor(amount / 500)
r = amount % 500
c200 = math.floor(r / 2)
r %= 2
c100 = math.floor(r / 1)
r %= 1
c50 = math.floor(r / 0.5)
r %= 0.5
c20 = math.floor(r / 0.2)
r %= 0.2
c10 = math.floor(r / 0.1)
r %= 0.1
c5 = math.floor(r / 0.05)
r %= 0.05
c2 = math.floor(r / 0.02)
r %= 0.02
c1 = math.floor(r / 0.01)
r %= 0.01

if amount > 0:
    print("Dispensing %d 2EUR coin(s), %d 1EUR coin(s), %d 50cent coin(s), %d 20cent coin(s), %d 10cent coin(s), %d 5cent coins, %d 2cent coins, and %d 1cent coins." % (c200, c100, c50, c20, c10, c5, c2, c1))
elif amount == 0:
    print("Cannot withdraw 0EUR.")
else:
    print("Cannot withdraw negative values.")

以上代码是整个ATM的修改片段

当您在编译器中 运行 时,您输入一个值,例如 2.4,输出是 Dispensing 1 2EUR coin(s), 0 1EUR coin(s), 0 50cent coin(s), 1 20cent coin(s), 1 10cent coin(s), 1 5cent coins, 2 2cent coins, and 0 1cent coins.,总计为 2.39EUR,而不是2.4EUR.

请帮忙,我卡住了。我已经在这两天了,我似乎找不到问题所在(这就是我在 Whosebug 上的原因)。

发生这种情况是因为浮点数不是很好的四舍五入数字。尽管控制台可能会告诉您 2.4%2 等于 0.4,但在内部数字存储为 0.39999999...因此,在某些时候,您会例如 0.4%0.2,期望收到 0,但实际模数将是 0.3999999...%0.2,这将是 return 0.19999999,但显示 0.2.

解决这个问题的简单方法总是四舍五入您的模运算。将 r%=0.2 写成 r=round(r%0.2, 1)。这里你说把r%0.2的return四舍五入到一位小数。

处理货币的正确方法是使用Decimal class。您只需将您的数字转换为 Decimal,然后所有操作都会正确舍入。

另一种方法是处理美分而不是小数。在这种情况下,2.4 将是 240 美分,那么您只需使用整数作为运算符即可。