为什么在Python中 -22 // 10 返回 -3?


在Python中,-22//10 返回 -3 是因为地板除的概念,也就是双斜杠运算符。// 是双斜杠,即算术运算符。让我们首先了解一下它。

Python中的地板除

操作数的除法,结果是商,其中小数点后的数字被移除。但是,如果其中一个操作数为负数,则结果向下取整,即舍入到零以外(朝负无穷大)。

在Python中,// 是双斜杠运算符,即地板除。// 运算符用于执行将结果向下舍入到最接近整数的除法。// 运算符的使用非常简单。我们还将结果与单斜杠除法进行比较。让我们首先看看语法:

a 和 b 分别是第一个和第二个数字

a // b

//(双斜杠)运算符示例

让我们来看一个在Python中实现双斜杠运算符的例子:

a = 37 b = 11 # 1st Number print("The 1st Number = ",a) # 2nd Number print("The end Number = ",b) # Dividing using floor division res = a // b print("Result of floor division = ", res)

输出

('The 1st Number = ', 37)
('The end Number = ', 11)
('Result of floor division = ', 3)

使用负数实现 //(双斜杠)运算符

示例

我们将尝试使用负数作为输入来使用双斜杠运算符。让我们看看这个例子

# A negative number with a positive number a = -37 b = 11 # 1st Number print("The 1st Number = ",a) # 2nd Number print("The end Number = ",b) # Dividing using floor division res = a // b print("Result of floor division = ", res)

输出

('The 1st Number = ', -37)
('The end Number = ', 11)
('Result of floor division = ', -4)

示例

正如您在上面的输出中看到的,使用负数并没有影响舍入。结果向下舍入。现在,我们可以用双斜杠运算符检查 -22 // 10:

# A negative number with a positive number a = -22 b = 10 # 1st Number print("The 1st Number = ",a) # 2nd Number print("The end Number = ",b) # Dividing using floor division res = a // b print("Result of floor division = ", res)

输出

('The 1st Number = ', -22)
('The end Number = ', 10)
('Result of floor division = ', -3)

更新于:2022年9月19日

275 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.