使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
当前回答
Python 3
操作 结果 笔记 X / y x和y的商 X // y x和y的底商 (1) 注: 也称为整数除法。结果值是一个整型,尽管结果的类型不一定是int。结果总是趋近于负无穷:1//2等于0,(-1)//2等于-1,1//(-2)等于-1,(-1)//(-2)等于0。
Python 2
Operation Result Notes x / y quotient of x and y (1) x // y (floored) quotient of x and y (4)(5) Notes: 1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value. 4. Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate. 5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
其他回答
总结
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)。 当意义的丧失不可忽视时,我们会得到错误的结果。
>>> print 5.0 / 2
2.5
>>> print 5.0 // 2
2.0
前面的答案都很好。我想再补充一点。在某些情况下,它们会得到相同的商。之后,除法运算符(//)可以正常工作,但除法(/)运算符不行:
>>> int(755349677599789174 / 2) # Wrong answer
377674838799894592
>>> 755349677599789174 // 2 # Correct answer
377674838799894587
方程的答案四舍五入到下一个较小的整数或以。0作为小数点的浮点数。
>>>print 5//2
2
>>> print 5.0//2
2.0
>>>print 5//2.0
2.0
>>>print 5.0//2.0
2.0
Python 2。x澄清:
为Python阐明2。X线,/既不是层除法也不是真除法。
当两个参数都为int时,/为整除;但当其中一个参数为float时,/为真除法。