Python math.remainder() 方法



Python 的 math.remainder() 方法用於計算一個數除以另一個數的餘數。數學上表示為:

remainder(x, y) = x − y × ⌊x/y⌋

其中,x 是被除數,y 是除數,⌊.⌋ 表示下取整方法,返回小於或等於引數的最大整數。例如,如果 "x = 10.5" 和 "y = 3.0",則 "math.remainder(10.5, 3.0)" 將計算餘數為 10.5 − 3.0 × ⌊10.5/3.0⌋ = 1.5。

語法

以下是 Python math.prod() 方法的基本語法:

math.remainder(x, y)

引數

此方法接受以下引數:

  • x − 被除數(被除的數)。

  • y − 除數(x 被除的數)。

返回值

該方法返回 "x" 除以 "y" 的餘數。

示例 1

在下面的示例中,我們使用 math.remainder() 方法計算 10 除以 3 的餘數:

import math
result = math.remainder(10, 3)
print("The result obtained is:",result)         

輸出

獲得的輸出如下:

The result obtained is: 1.0

示例 2

當我們將負被除數作為引數傳遞給 remainder() 方法時,它會保留被除數的符號並相應地返回它:

import math
result = math.remainder(-10, 3)
print("The result obtained is:",result)  

輸出

以上程式碼的輸出如下:

The result obtained is: -1.0

示例 3

現在,我們使用 math.remainder() 方法計算被除數 10 除以負除數 -3 的餘數:

import math
result = math.remainder(10, -3)
print("The result obtained is:",result) 

輸出

我們得到如下所示的輸出:

The result obtained is: 1.0

示例 4

在這個例子中,我們透過傳遞浮點數作為引數來計算餘數:

import math
result = math.remainder(7.5, 3.5)
print("The result obtained is:",result) 

輸出

產生的結果如下所示:

The result obtained is: 0.5
python_maths.htm
廣告