為什麼在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 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告