Python divmod() 函数用法

2023-09-17 22:27:36

divmod() 方法将两个非复数作为参数,并返回两个数字的元组,其中第一个数字是商,第二个数字是余数。

语法:

divmod(number1, number2)

参数:

  1. 数字 1:分子。
  2. 数字2:分母。

返回值:

通过计算 (数字 1//数字 2, 数字 1 % 数字 2) 返回元组(商,余数)。

下面的示例返回各种数字的商和余数。

print("Divmod of (6,2) is: ", divmod(6,2))
print("Divmod of (8,3) is: ", divmod(8,3))
print("Divmod of (7,2) is: ", divmod(7,2))
print("Divmod of (3,10) is: ", divmod(3,19))
<

输出:

Divmod of (6,2) is:  (3, 0)
Divmod of (8,3) is:  (2, 2)
Divmod of (7,2) is:  (3, 1)
Divmod of (3,10) is:  (0, 3)

如果传递浮点数,结果将是 (math.floor(number1/number2), number1 % number2),如下所示。

print("Divmod of (6.5, 2) is: ", divmod(6.5, 2))
print("Divmod of (6, 2.5) is: ", divmod(6, 2.5))

输出:

Divmod of (6.5, 2) is: (3.0, 0.5)
Divmod of (6, 2.5) is: (2.0, 1.0)

传递复数会引发错误。

print("Divmod of (6.5, 2) is: ", divmod(3 + 2j, 6 + 8j))

输出:

TypeError: can't take floor or mod of complex number.