如何固定我的模数滤波器以正确计算每张钞票的金额?

问题描述 投票:0回答:1

我主要使用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

[请帮助,我被困住了。我已经在这里待了两天了,而且我似乎找不到问题所在(这就是为什么我在StackOverflow上的原因)。

python modulus
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.