42% 10 = 2

That is correct, but

-42 % 10 = 8

Why?

That is correct, but

-42 % 10 = 8

Why?

asked March 23rd 20 at 19:00

2 answers

answered on

Solution

Because just the same from a mathematical point of view, Python unlike Serznyh languages, it is doing the right thing.

UP: Well, since such issues, it is necessary to read the modulo operator, and tenderloin out:

```
-42 // 10 = -5
-42 % 10 = 8
---------------
-5 * 10 + 8 = -42
```

UP: Well, since such issues, it is necessary to read the modulo operator, and tenderloin out:

Division with a remainder ("the dividend") to b (the divisor) means finding integers q and r that the validity of the equation:

a=b*q+r

answered on

Solution

The fact that when dividing with a remainder, the remainder must be positive. This means that when dividing with a remainder of negative numbers, we need a positive balance to find from a SMALLER number. It turns out that when dividing with remainder 42 10 we reject less delimuyu a part: 40. Remains 2. So by dividing -42 with the remainder we discard less delimuyu a part of: -50, leaving a positive balance equal to -42: -50 - (-42) = -50 + 42 = 8.

Find more questions by tags Python