欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 中的divmod数字处理函数浅析

程序员文章站 2024-03-02 20:49:34
divmod(a,b)函数 中文说明: divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数 返回结果类型为tuple 参数: a,b可以为数字...

divmod(a,b)函数

中文说明:

divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数

返回结果类型为tuple

参数:

a,b可以为数字(包括复数)

版本:

在python2.3版本之前不允许处理复数,这个大家要注意一下

英文说明:

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

Changed in version 2.3: Using divmod() with complex numbers is deprecated.

python代码实例:

>>> divmod(9,2)
(4, 1)
>>> divmod(11,3)
(3, 2)
>>> divmod(1+2j,1+0.5j)
((1+0j), 1.5j)

PS:Python标准库:内置函数divmod(a, b)

本函数是实现a除以b,然后返回商与余数的元组。如果两个参数a,b都是整数,那么会采用整数除法,结果相当于(a//b, a % b)。如果a或b是浮点数,相当于(math.floor(a/b), a%b)。

例子:

#divmod() 
print('divmod(2, 4):', divmod(2, 4)) 
print('divmod(28, 4):', divmod(28, 4)) 
print('divmod(27, 4):', divmod(27, 4)) 
print('divmod(25.6, 4):', divmod(25.6, 4)) 
print('divmod(2, 0.3):', divmod(2, 0.3)) 

输出结果如下:

divmod(2, 4): (0, 2)
divmod(28, 4): (7, 0)
divmod(27, 4): (6, 3)
divmod(25.6, 4): (6.0, 1.6000000000000014)
divmod(2, 0.3): (6.0, 0.20000000000000007)

总结

以上所述是小编给大家介绍python divmod数字处理函数浅析,希望对大家有所帮助