+ 3
Can anybody explain me??? @_@
Why in Python -11//3 == -4 and why -11%3 == 1 While in C (for example) -11/3 == -3 (as expected) and -11%3 == -2
5 ответов
+ 3
In C, -11%3 is not 2, but -2. a%b is defined as (a/b*b)+a%b = a.
a/b = -3 (integer division)
-3 * b = -9
-9 + a%b = -11
=> a%b = -2
+ 2
-11//3 finds the greatest multiple of 3 less than or equal to -11 (here that’s -12) and returns that number divided by 3, hence -4.
Similar with -11%3 - it finds the greatest multiple of 3 less than or equal to -11 and returns the difference.
+ 1
First case is floor division operator "//". The number is rounded down to the closest number to negative infinity => -4. For the second case you can read more here: https://stackoverflow.com/questions/10063546/modulo-for-negative-dividends-in-JUMP_LINK__&&__python__&&__JUMP_LINK
0
Russ but why in others languages (like C) it is not so?