加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

为什么Python3中的print函数是十进制数?

发布时间:2020-12-16 22:41:04 所属栏目:Python 来源:网络整理
导读:参见英文答案 Floating point behavior in Python 2.6 vs 2.7????????????????????????????????????1个 如果我在python2.7控制台上运行它,它给我输出为: 1.2 - 1.00.19999999999999996 print 1.2 - 1.0 0.2 我在python3.5.2中运行相同的操作 1.2 - 1.00.199

参见英文答案 > Floating point behavior in Python 2.6 vs 2.7????????????????????????????????????1个
如果我在python2.7控制台上运行它,它给我输出为:

>>> 1.2 - 1.0
0.19999999999999996

>>> print 1.2 - 1.0 
0.2

我在python3.5.2中运行相同的操作

>>> 1.2 - 1.0
0.19999999999999996

>>> print(1.2 - 1.0)
0.19999999999999996

我想知道为什么在python2.7.12打印语句只给我0.2但在python3.5.2打印函数给我0.19999999999999996.

最佳答案
这不是由于打印的变化,而是浮动的__str__函数的变化,它隐式调用.因此,当你打印时,它会调用如下:

# For Python 2.7
>>> print (1.2 - 1.0).__str__()
0.2

为了按原样显示浮动值,您可以显式调用.__ repr__:

>>> print (1.2 - 1.0).__repr__()
0.19999999999999996

有关更多详细信息,请查看Martjin’s answer on Floating point behavior in Python 2.6 vs 2.7,其中说明:

In Python 2.7 only the representation changed,not the actual values. Floating point values are still binary approximations of real numbers,and binary fractions don’t always add up to the exact number represented.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读