使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
当前回答
前面的答案都很好。我想再补充一点。在某些情况下,它们会得到相同的商。之后,除法运算符(//)可以正常工作,但除法(/)运算符不行:
>>> int(755349677599789174 / 2) # Wrong answer
377674838799894592
>>> 755349677599789174 // 2 # Correct answer
377674838799894587
其他回答
Python 3。x澄清
只是为了补充之前的一些答案。
必须指出的是:
A // b
是楼层划分。如: math.floor (a / b) 不是整数除法。如: int (a / b) 不是四舍五入到0的浮点除法。如: 轮(a / b, 0)
因此,当涉及到正数和负数时,行为方式是不同的,如下例所示:
1 // 2为0,即:
math.floor(1/2)
-1 // 2为-1,即:
math.floor(-1/2)
/→浮点除法
//→楼层划分
让我们看看Python 2.7和Python 3.5中的一些例子。
Python 2.7.10 vs. Python 3.5
print (2/3) ----> 0 Python 2.7
print (2/3) ----> 0.6666666666666666 Python 3.5
Python 2.7.10 vs. Python 3.5
print (4/2) ----> 2 Python 2.7
print (4/2) ----> 2.0 Python 3.5
现在,如果你想拥有(在Python 2.7中)与Python 3.5相同的输出,你可以执行以下操作:
Python 2.7.10
from __future__ import division
print (2/3) ----> 0.6666666666666666 # Python 2.7
print (4/2) ----> 2.0 # Python 2.7
然而在Python 2.7和Python 3.5中,层划分没有任何区别。
138.93//3 ---> 46.0 # Python 2.7
138.93//3 ---> 46.0 # Python 3.5
4//3 ---> 1 # Python 2.7
4//3 ---> 1 # Python 3.5
方程的答案四舍五入到下一个较小的整数或以。0作为小数点的浮点数。
>>>print 5//2
2
>>> print 5.0//2
2.0
>>>print 5//2.0
2.0
>>>print 5.0//2.0
2.0
总结
x//y:精确的整数除法 int(x/y) OR math.floor(x/y):不精确的整数除法(但几乎正确) X /y:浮点除法(没有意义)
显著计算结果
import math
N = 1004291331219602346 # huge number
print(N//100) #=> 10042913312196023 is correct answer
print(math.floor(N/100)) #=> 10042913312196024 is wrong answer
print(math.ceil(N/100)) #=> 10042913312196024 is wrong answer
print(int(N/100)) #=> 10042913312196024 is wrong answer
考虑
考虑int(x/y)的取值。 首先,Python计算表达式x/y并得到不精确的浮点数z。 其次,Python计算表达式int(z)。 当意义的丧失不可忽视时,我们会得到错误的结果。
5.0//2的结果是2.0,而不是2,因为//操作符返回值的返回类型遵循Python强制转换(类型强制转换)规则。
Python促进低数据类型(整数)到高数据类型(浮点数)的转换,以避免数据丢失。