我有两张单子:
salePrices = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95]
percents = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
然后,使用这个for循环,我遍历每一个百分比并计算折扣价格。你知道吗
for percent in percents:
for salePrice in salePrices:
newPrice = salePrice - ((percent / 100) * salePrice)
print("\t" + "{0:.2f}".format(newPrice), end = " ")
print()
这一切工作正常,除了一个问题:一些计算的值没有正确舍入。你知道吗
例如,14.95-(0.1*14.95)=13.455,应该通过.format()四舍五入到13.46。但是,打印的值是13.45。你知道吗
是我做错了什么,还是方法、格式本身有问题?你知道吗
你的问题是:
不,在IEEE doubles中,
14.95 - (0.1 * 14.95)
是13.454999999999998
。精确到13.45
。你知道吗Here's the obligatory link to What Every Computer Scientist Should Know About Floating-Point Arithmetic。你知道吗
如果您希望} 而不是
14.95
实际上正好是14.95,而不是最接近14.95的二进制分数,您可能希望使用^{float
。当然Decimal
也是不精确的,但是最接近14.95的小数点显然是14.95。:)相关问题 更多 >
编程相关推荐