Python整数除法产生浮点数

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 

这是打算? 我强烈记得早期版本返回int/int=int ? 我应该怎么做,是否有一个新的分工操作员,或者我必须总是施放?

看一下PEP-238 :更换部门操作员

//操作员可以明确地请求地板划分。

哎呀,马上find2//2

被接受的答案已经提到了PEP 238 。 我只是想在没有阅读整个PEP的情况下,对那些对发生的事情感兴趣的人在幕后添加一些快速回顾。

Python将运算符(如+-*/映射到特殊函数,例如a + b等同于

 a.__add__(b) 

关于在Python 2中的划分,默认情况下只有/哪些映射到__div__ ,结果取决于inputtypes(如intfloat )。

Python 2.2引入了__future__特性division ,它通过以下方式改变了分区语义(TL; PEP 238的DR):

  • /映射到__truediv__ ,它必须“返回分区math结果的合理近似值”(引自PEP 238)
  • //映射到__floordiv__ ,它应该返回/

在Python 3.0中,PEP 238的变化成为默认行为,Python的对象模型中没有更多的特殊方法__div__

如果你想在Python 2和Python 3中使用相同的代码

 from __future__ import division 

并坚持///的PEP 238语义。

希望它能立即帮助别人。

Python 2.7和Python 3中除法运算符的行为

在Python 2.7中:默认情况下,除法运算符将返回整数输出。

得到的结果是双倍1.0到“除数或除数”

 100/35 => 2 #(Expected is 2.857142857142857) (100*1.0)/35 => 2.857142857142857 100/(35*1.0) => 2.857142857142857 

在Python 3中

 // => 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