在Python中//是什么意思(一文搞懂Python中的运算符)

 分类:IT知识时间:2023-07-20 07:31:03点击:

在 Python 中,使用双斜杠运算符执行下层除法。此运算符将第一个数字除以第二个数字,并将结果向下舍入为最接近的整数(或整数)。////

在本文中,我将向您展示如何使用运算符并将其与常规除法进行比较,以便您可以看到它的工作原理。//

不过,它并没有就此结束 - 您还将了解与双斜杠运算符同义的Python数学方法。//

我们将涵盖的内容

  • // 运算符的基本语法
  • 地板划分示例
  • 双斜杠 // 运算符的工作方式类似于 math.floor()
  • 双斜杠如何 // 操作员在幕后工作
  • 结论

运算符的基本语法//

要使用双斜杠运算符,您可以执行几乎与常规除法中相同的操作。唯一的区别是,使用双斜杠代替单斜杠://///

firstNum // secondNum

地板划分示例

在下面的示例中,12 乘以 5 的楼层划分得到 2:

num1 = 12 num2 = 5 num3 = num1 // num2 print("floor division of", num1, "by", num2, "=", num3) # Output: floor division of 12 by 5 = 2

而 12 乘以 5 的常规除法等于 2.4。即 2 余数 4:

num2 = 5 num3 = num1 / num2 print("normal division of", num1, "by", num2, "=", num3) # Output: normal division of 12 by 5 = 2.4

这向您显示运算符将两个数字的除以结果向下舍入为最接近的整数。//

即使小数点为 9,运算符仍会将结果向下舍入为最接近的整数。//

num1 = 29num2 = 10num3 = num1 / num2 num4 = num1 // num2 print("normal division of", num1, "by", num2, "=", num3) print("but floor division of", num1, "by", num2, "=", num4) """ Output: normal division of 29 by 10 = 2.9 but floor division of 29 by 10 = 2 """

如果您使用负数执行楼层除法,则结果仍将向下舍入。

为了让你的大脑为结果做好准备,向下舍入一个负数意味着远离0。因此,-12 除以 5 得到 -3。不要感到困惑 - 即使乍一看,核磁机似乎越来越“大”,但它实际上变得越来越小(从零/更大的负数进一步)。

num1 = -12 num2 = 5 num3 = num1 // num2 print("floor division of", num1, "by", num2, "=", num3) # floor division of -12 by 5 = -3

双斜杠运算符的工作方式如下//math.floor()

在 Python 中,将数字向下舍入为最接近的整数,就像双斜杠运算符一样。math.floor()//

因此,它是操作员的替代方案,因为他们在幕后做同样的事情。math.floor()//

下面是一个示例:

importmath num1 = 12num2 = 5num3 = num1 // num2 num4 = math.floor(num1 / num2) print("floor division of", num1, "by", num2, "=", num3) print("math.floor of", num1, "divided by", num2, "=", num4) """ Output: floor division of 12 by 5 = 2 math.floor of 12 divided by 5 = 2 """

您可以看到它执行与运算符相同的操作。math.floor()//

双斜杠运算符如何在幕后工作//

使用运算符将两个数字除以时,在后台调用的方法是 .//__floordiv__()

您也可以直接使用此方法代替运算符:__floordiv__()//

num1 = 12num2 = 5num3 = num1 // num2 num4 = num1.__floordiv__(num2) print("floor division of", num1, "by", num2, "=", num3) print("using the floordiv method gets us the same value of", num4) """ Output: floor division of 12 by 5 = 2 using the floordiv method gets us the same value of 2 """

结论

在本文中,您学习了如何使用双斜杠运算符以及它在后台的工作原理。//

此外,您还了解了运算符的两种选择 - 以及方法。//math.floor()__floordiv__()

除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址: