+ 3
Can anybody explain me??? @[email protected]
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 Answers
+ 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-python
0
Russ but why in others languages (like C) it is not so?
0
ivan That I can’t tell you. It’s just the way Python was designed.
Hot today
Python — File Handling
2 Votes
Help me
0 Votes
What’s wrong?
2 Votes
Question is write a c program to print prime numbers up to n and print the largest number in array.
1 Votes
Achievements on Sololearn
1 Votes
How to draw in the console?
0 Votes