Find the division remainder of a number

前端 未结 12 1199
刺人心
刺人心 2020-11-28 07:30

How could I go about finding the division remainder of a number in Python?

For example:
If the number is 26 and divided number is 7, then the division remainder

相关标签:
12条回答
  • 2020-11-28 08:20

    We can solve this by using modulus operator (%)

    26 % 7 = 5;

    but 26 / 7 = 3 because it will give quotient but % operator will give remainder.

    0 讨论(0)
  • 2020-11-28 08:28

    From Python 3.7, there is a new math.remainder() function:

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

    Output:

    -2.0  # not 5
    

    Note, as above, it's not the same as %.

    Quoting the documentation:

    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 describes the rationale for creating the new function.

    0 讨论(0)
  • 2020-11-28 08:30

    Use the % instead of the / when you divide. This will return the remainder for you. So in your case

    26 % 7 = 5
    
    0 讨论(0)
  • 2020-11-28 08:32

    If you want the remainder of your division problem, just use the actual remainder rules, just like in mathematics. Granted this won't give you a decimal output.

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

    If you want to make this in a calculator format, just substitute valone = 8 with valone = int(input("Value One")). Do the same with valtwo = 3, but different vairables obviously.

    0 讨论(0)
  • 2020-11-28 08:34

    you can define a function and call it remainder with 2 values like rem(number1,number2) that returns number1%number2 then create a while and set it to true then print out two inputs for your function holding number 1 and 2 then print(rem(number1,number2)

    0 讨论(0)
  • 2020-11-28 08:35

    The remainder of a division can be discovered using the operator %:

    >>> 26%7
    5
    

    In case you need both the quotient and the modulo, there's the builtin divmod function:

    >>> seconds= 137
    >>> minutes, seconds= divmod(seconds, 60)
    
    0 讨论(0)
提交回复
热议问题