如何在Python中找到一个数的除法余数呢?

例如: 如果这个数是26,整除数是7,那么整除余数是5。 (因为7+7+7=21,26-21=5。)


有关简单的可整除性测试,请参见如何检查一个数是否能被另一个数整除。


你正在寻找模运算符:

a % b

例如:

>>> 26 % 7
5

当然,也许他们希望您自己实现它,这也不会太难。


除法时用%代替/。这将为您返回余数。所以在你的案例中

26 % 7 = 5

取模是正确的答案,但如果你手动做的话,这应该是可行的。

num = input("Enter a number: ")
div = input("Enter a divisor: ")

while num >= div:
    num -= div
print num

除法的余数可以使用运算符%来发现:

>>> 26%7
5

如果你同时需要商和模,有一个内置的divmod函数:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

如果你想避免取模,你也可以使用四个基本操作的组合:)

26 - (26 // 7 * 7) = 5

26 % 7(你将得到余数)

26 / 7(你会得到除数,可以是浮点值)

26 // 7(你将得到除数,只有整数值)


如果你想求除法问题的余数,就用实际的余数法则,就像数学一样。当然,这不会给你一个十进制输出。

valone = 8
valtwo = 3
x = valone / valtwo
r = valone - (valtwo * x)
print "Answer: %s with a remainder of %s" % (x, r)

如果你想用计算器的形式,只要代入valone = 8 用valone = int(输入(“值一”))。对valtwo = 3做同样的处理,但显然变量不同。


从Python 3.7开始,有一个新的math.remainder()函数:

from math import remainder
print(remainder(26,7))

输出:

-2.0  # not 5

注意,如上所述,它与%不同。

引用文档:

math.remainder(x, y) Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y). Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x. On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

Issue29962描述了创建新函数的基本原理。


我们可以用模算子(%)来解决这个问题

26%7 = 5;

但 26 / 7 = 3,因为它会给出商,而%运算符会给出余数。


如果你想在一行代码中得到商和余数(更通用的情况),使用:

quotient, remainder = divmod(dividend, divisor)
#or
divmod(26, 7)

你可以用模算子求余数 例子

a=14
b=10
print(a%b)

它会输出4


您可以定义一个函数,并将其称为具有2个值的remainder,如rem(number1,number2),返回number1%number2 然后创建一个while,并将其设为true然后为持有编号1和2的函数输出两个输入然后输出(rem(number1,number2)


这是Python中余数的整数版本,它的结果应该与C的“%”操作符相同:

def remainder(n, d):
    return (-1 if n < 0 else 1) * (abs(n) % abs(d))

预期结果:

remainder(123, 10)   ==  3
remainder(123, -10)  ==  3
remainder(-123, 10)  == -3
remainder(-123, -10) == -3