Python整数除法产生浮点数Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or
"license" for more information.>>> 2/21.0这是故意的吗?我强烈记得以前的版本返回int/int=int?我应该怎么做,是否有一个新的除法操作符,还是我必须总是投?
2 回答

SMILET
TA贡献1796条经验 获得超4个赞
Python2.7和Python3中除法操作符的行为
在Python2.7中:默认情况下,除法操作符将返回整数输出。
100/35 => 2 #(Expected is 2.857142857142857)(100*1.0)/35 => 2.857142857142857100/(35*1.0) => 2.857142857142857
在Python 3中
// => used for integer output/ => used for double output100/35 => 2.857142857142857100//35 => 2100.//35 => 2.0 # floating-point result if divsor or dividend real

慕码人8056858
TA贡献1803条经验 获得超6个赞
Python映射操作符,如+
, -
, *
和/
对于特殊的功能,例如:a + b
等于
a.__add__(b)
对于Python 2中的除法,默认情况下只有/
哪个映射到__div__
结果取决于输入类型。int
, float
).
Python 2.2引入了__future__
特征division
,它以下列方式改变了划分语义(TL;PEP 238的DR):
映射到/
它必须“返回除法的数学结果的合理近似”(引用PEP 238)。__truediv__
映射到//
,这应该会返回.的泛泛结果。__floordiv__
/
在Python3.0中,PEP 238的更改成为默认行为,没有更特殊的方法__div__
在Python的对象模型中。
如果您想在Python 2和Python 3中使用相同的代码,请使用
from __future__ import division
的PEP 238语义/
和//
.
添加回答
举报
0/150
提交
取消