python divmod_Python divmod()

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值