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

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


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


当前回答

这是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

其他回答

这是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

26 % 7(你将得到余数)

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

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

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

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