Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
在玩python时,我遇到了这个:
a = 1/(2.2 - 2) print a #prints out 5.0 print int(a) #prints out 4
我怀疑这个问题与二进制数表示有关(用二进制表示 1/5 就等于用十进制表示 1/3)。有人可以对此有所了解吗?
你的怀疑是完全正确的。根本原因是 2.2 不能完全表示为float:
float
In [38]: '%.20f' % 2.2 Out[38]: '2.20000000000000017764'
其余的由此而来:
In [45]: '%.20f' % (2.2 - 2) Out[45]: '0.20000000000000017764' In [46]: '%.20f' % (1 / (2.2 - 2)) Out[46]: '4.99999999999999555911'