调用类型(1/2)返回整数?

5 python python-2.x

所以我注意到了:

print type(1/2) 
Run Code Online (Sandbox Code Playgroud)

返回一个整数,但它不应该是一个浮点数?

JRo*_*ite 7

试试type(1/2.0),这将返回浮动.其中一个数字必须是浮点值才能获得浮点数的返回值.

Python-2.x除法运算符遵循Classic Division.当呈现整数操作数时,经典除法截断小数位,返回一个整数(也称为地板除法).当给定一对浮点操作数时,它返回实际的浮点商(也就是真正的除法).

例:

>>> 1 / 2          # integer truncation (floor division)
0
>>> 1.0 / 2.0      # returns real quotient (true division)
0.5
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,除法的工作方式不同.type(1/2)将返回float类型.Python-3.x除法运算符遵循True Division.