Man*_*aar 0 python math integer floating python-3.x
如果"//"适用于整数,为什么此函数会打印浮点数?
>>> minimum = int((a + b) - math.fabs(a-b))//2
>>> print(type(minimum))
Run Code Online (Sandbox Code Playgroud)
//不表示将返回整数,运算符//被调用(floor division),但可以返回float或int它取决于操作数类型,例如: 9//2等于4和9.0//2.0等于4.0.那是浮动的.
5.6.二进制算术运算
在
/(部门)和//(楼科)运营商获得他们的论据商.数字参数首先转换为通用类型.普通或长整数除法产生相同类型的整数; "结果是数学划分的结果,'floor'功能应用于结果".除以零会引发ZeroDivisionError异常.
检查ideone的工作实例链接为Python3._:
下面的例子可能有助于理解之间的差异/以及//为什么//有用(阅读评论):
a = 9.0
b = 2.0
print a//b # floor division gives `4.0` instead of `4.5`
a = 9
b = 2
print a/b # int division because both `b` and `a` are `int` => `4.5`
print a//b # float division returns `4`
a = 9.0
b = 2
print a/b # float division gives `4.5` because `a` is a float
print a//b # floor division fives `4.0`
Run Code Online (Sandbox Code Playgroud)
输出:
4.0 # you doubt
4.5
4
4.5 # usefulness of //
4.0
Run Code Online (Sandbox Code Playgroud)
现在在你的表达式中,两个操作数都是int如此,答案是int类型:
int((a + b) - math.fabs(a-b)) // 2
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^
# int due to casting int => `minimum` as int
Run Code Online (Sandbox Code Playgroud)
因此,//如果任何操作数是浮点数,但是幅度等于floor,则可以导致浮点数.