Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # floating-point result if divsor or dividend real
4 回答
看看PEP-238:更改分部操作员
哎呀,马上找到
2//2
.希望它可以立即帮助某人 .
Python 2.7和Python 3中除法运算符的行为
得到的结果是双 multiple 1.0 到"dividend or divisor"
接受的答案已经提到PEP 238 . 我只想在幕后为那些对正在发生的事情感兴趣而不阅读整个PEP的人添加一个快速浏览 .
Python将
+
,-
,*
和/
之类的运算符映射到特殊函数,例如a + b
相当于关于Python 2中的除法,默认情况下只有
/
映射到__div__
,结果取决于输入类型(例如int
,float
) .Python 2.2引入了
__future__
特性division
,它以下列方式改变了除法语义(TL; PEP 238的DR):/
映射到__truediv__
,必须"return a reasonable approximation of the mathematical result of the division"(引自PEP 238)//
映射到__floordiv__
,它应返回/
的覆盖结果使用Python 3.0,PEP 238的更改成为默认行为,Python的对象模型中没有更多特殊方法
__div__
.如果你想在Python 2和Python 3中使用相同的代码
并坚持
/
和//
的PEP 238语义 .