a = 1
for x in range(5):
a += 0.1
print(a)
这是结果:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
我该如何解决这个问题? round() 函数是唯一的方法吗?我可以在设置变量值之前设置变量的精度吗?
请您参考如下方法:
can i set the precision of a variable before setting the value?
使用 decimal模块,不像float() , 提供任意精度并且可以精确表示十进制数:
>>> from decimal import Decimal, getcontext
>>>
>>> getcontext().prec = 5
>>>
>>> a = Decimal(1)
>>>
>>> for x in range(5):
... a += Decimal(0.1)
... print(a)
...
1.1000
1.2000
1.3000
1.4000
1.5000
