python divmod_Python divmod()

薛望
2023-12-01

python divmod

Python divmod() function is used to perform division on two input numbers. The numbers should be non-complex and can be written in any format such as decimal, binary, hexadecimal etc.

Python divmod()函数用于对两个输入数字进行除法。 数字应该是非复杂的,并且可以以任何格式编写,例如十进制,二进制,十六进制等。

Python divmod() (Python divmod())

Python divmod() syntax is:

Python divmod()语法为:

divmod(a, b)

The output is a tuple consisting of their quotient and remainder when using integer division.

使用整数除法时,输出是一个由它们的商和余数组成的元组

For integer arguments, the result is the same as (a // b, a % b).

对于整数参数,结果与(a // b,a%b)相同。

For floating point numbers the result is (q, a % b), where q is usually (math.floor(a / b), a % b). In any case q * b + a % b is very close to a.

对于浮点数,结果为(q,a%b),其中q通常为(math.floor(a / b),a%b)。 无论如何,q * b + a%b非常接近a。

If a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

如果%b不为零,则它的符号与b相同,并且0 <= abs(a%b)<abs(b)。

带有整数的Python divmod()示例 (Python divmod() example with integers)

# simple example, returns (a // b, a % b) for integers
dm = divmod(10, 3)
print(dm)

x, y = divmod(10, 3)
print(x)
print(y)

dm = divmod(0xF, 0xF)  # hexadecimal
print(dm)

Output:

输出:

(3, 1)
3
1
(1, 0)

带有浮点数的Python divmod()示例 (Python divmod() example with floats)

# floats, returns usually (math.floor(a / b), a % b)
dm = divmod(10.3, 3)
print(dm)

dm = divmod(11.51, 3)
print(dm)

dm = divmod(-11.51, 3)
print(dm)

Output:

输出:

(3.0, 1.3000000000000007)
(3.0, 2.51)
(-4.0, 0.4900000000000002)

Notice that in case of floating points, the q * b + a % b is very close to a in some cases.

注意,在浮点情况下, q * b + a % b在某些情况下非常接近a

带有复数的divmod() (divmod() with complex numbers)

If we pass complex numbers as argument, we will get TypeError.

如果我们将复数作为参数传递,则会得到TypeError

dm = divmod(3 + 2J, 3)

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

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

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22813/python-divmod

python divmod

 类似资料:

相关阅读

相关文章

相关问答