a = 1
for x in range(5):
a += 0.1
print(a)
这是结果:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
我怎样才能解决这个问题?是个round()
功能唯一的方法?我可以在设置变量值之前设置变量的精度吗?
我可以在设置值之前设置变量的精度吗?
Use the decimal https://docs.python.org/3/library/decimal.html模块,不同于float() https://docs.python.org/3/library/functions.html?highlight=float#float,提供任意精度并且可以精确地表示十进制数:
>>> from decimal import Decimal, getcontext
>>>
>>> getcontext().prec = 5
>>>
>>> a = Decimal('1')
>>>
>>> for x in range(5):
... a += Decimal('0.1') # note the use of `str` here
... print(a)
...
1.1000
1.2000
1.3000
1.4000
1.5000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)