一日一技:Python里面的//并非作了除法之后取整

一日一技:Python里面的//并非作了除法之后取整
一日一技:Python里面的//并非作了除法之后取整python

在Python 3里面,咱们作除法的时候会遇到 a/b 和 a//b两种写法:ide

>>> 10 / 3
3.3333333333333335
>>> 10 // 3
>>> 3

因而可能有人会认为, a//b至关于 int(a/b)。测试

但若是再进一步测试,你会发现:code

>>> int(-10/3)
-3
>>> -10 // 3
>>> -4

看到这里,可能有人意识到, //彷佛是向下取整的意思,例如 -3.33向下取整是 -4。blog

那么咱们再试一试向下取整:ci

>>> import math
>>> math.floor(-10/3)
-4
>>> -10//3
-4

看起来已是这么一回事了。可是若是你把其中一个数字换成浮点数,就会发现事情并无这么简单:input

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-divisionit

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.io

结果的类型将会是 a和 b的公共类型。若是 a是整数, b是浮点数,那么首先他们会被转换为公共类型,也就是浮点数(由于整数转成浮点数不过是末尾加上 .0,不会丢失信息,可是浮点数转换为整数,可能会把小数部分丢失。因此整数何浮点数的公共类型为浮点数),而后两个浮点数作 //之后的结果仍是浮点数。

kingname攒钱给产品经理买房。

相关文章
相关标签/搜索