
在Python 3里面,我们做除法的时候会遇到 a/b 和 a//b两种写法:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
于是可能有人会认为, a//b相当于 int(a/b)。
但如果再进一步测试,你会发现:
>>> int(-10/3)
-3
>>> -10 // 3
-4
看到这里,可能有人意识到, //似乎是向下取整的意思,例如 -3.33向下取整是 -4。
那么我们再试一试向下取整:
>>> import math
>>> math.floor(-10/3)
-4
>>> -10//3
-4
看起来已经是这么一回事了。但是如果你把其中一个数字换成浮点数,就会发现事情并没有这么简单:
import math
>>> math.floor(-10/3.0)
-4
>>> -10//3.0
-4.0
当有一个数为浮点数的时候, //的结果也是浮点数,但是 math.floor的结果是整数。
这个原因可以参看Python PEP-238的规范:ttps://www.python.org/dev/peps/pep-0238/#semantics-of-floor-division
except that the result type will be the common type into which a and b are coerced before the operation. Specifically, if a and b are of the same type, a//b will be of that type too. If the inputs are of different types, they are first coerced to a common type using the same rules used for all other arithmetic operators.
结果的类型将会是 a和 b的公共类型。如果 a是整数, b是浮点数,那么首先他们会被转换为公共类型,也就是浮点数(因为整数转成浮点数不过是末尾加上 .0,不会丢失信息,但是浮点数转换为整数,可能会把小数部分丢失。所以整数何浮点数的公共类型为浮点数),然后两个浮点数做 //以后的结果还是浮点数。
本文详细解释了Python3中两种除法运算符a/b与a//b的区别,通过实例展示了整数除法与向下取整之间的微妙差异,并探讨了在操作不同数据类型时这些运算符的行为变化。
912

被折叠的 条评论
为什么被折叠?



