您的位置:首页 > 编程语言 > Python开发

Python: 探究py2与py3除法的区别

2017-08-15 10:16 309 查看

起因

在用python2解释器运行python3代码的时候,出现了bug。debug后发现是因为python3中的/ 原本表示 精确除法,却被python2解释器解释成了 地板除,最终导致了错误。因此我上网查阅了相关资料,并总结如下表:

总结

version///
py2整数除法时为地板除,浮点数除法时为精确除地板除
py3精确除法地板除

Test

x = y = 10
x /= 2    # 精确除
y //= 2    # 地板除
print(x, type(x))    # 5.0 <class 'float'>
print(y, type(y))    # 5 <class 'int'>


user@user:~$ python
Python 2.7.13 |Anaconda 2.4.1 (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org >>> 9/2
4
>>> 9.0/2
4.5
>>> 9//2
4
>>> 9.0//2
4.0
>>> float(9)/2
4.5
>>> from __future__ import division
>>> 9/2
4.5
>>>
>>>
[3]+  Stopped                 python
>>>
>>>
user@user:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/2
4.5
>>> 9//2
4
>>> 9.0//2
4.0
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: