负数的楼层划分 [英] Floor division with negative number
问题描述
表达式 6 // 4
产生 1
,其中底数除法在除以一个数字后产生整数。
The expression 6 // 4
yields 1
, where floor division produces the whole number after dividing a number.
但是带有负数,为什么 -6 // // 4
返回 -2
?
But with a negative number, why does -6 // 4
return -2
?
推荐答案
//
运算符明确地将显示在结果中。引用 二进制算术运算文档:
The //
operator explicitly floors the result. Quoting the Binary arithmetic operations documentation:
结果是对数学除法的结果应用了 floor函数。
the result is that of mathematical division with the ‘floor’ function applied to the result.
地板与四舍五入不一样;地板始终移动到较低的整数值。参见 math.floor()
函数:
Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor()
function:
返回 x 的下限,小于或等于的最大整数等于 x 。
Return the floor of x, the largest integer less than or equal to x.
对于 -6 // // 4
,首先是<$ c的结果$ c> -6 / 4 是计算得出的,因此 -1.5
。然后将下限移动到较低的整数值,因此 -2
。
For -6 // 4
, first the result of -6 / 4
is calculated, so -1.5
. Flooring then moves to the lower integer value, so -2
.
如果您想四舍五入,您必须明确地这样做;您可以使用 int()
函数进行真正的除法操作:
If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the int()
function on true division:
>>> int(-6 / 4)
-1
int( )
删除小数部分,因此始终舍入为零。
int()
removes the decimal portion, so always rounds towards zero instead.
这篇关于负数的楼层划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!