Non-positive number division is quite different in c++ and python programming langugages:
//c++:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2
So, as you can see, c++ is minimizing quotient.
However, python behaves like that:
#python
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -4
(-11) % 3 = 1
11 / (-3) = -4
11 % (-3) = -1
(-11) / (-3) = 3
(-11) % (-3) = -2
I can’t code my own division function behaving like c++, because I’ll use it for checking c++ calculator programs, and python does not support infix operators. Can I make python behaving like c++ while dividing integers in a simple way? For example, setting some flag or something like that?
As Thomas K said, use
math.fmodfor modulo, or if you really want you can define it yourself:And this function should emulate C-style division:
You said that you must use the
/and%operators. This is not possible, since you can’t override the operator for built-ins. You can however define your own integer type and operator overload the__div__and__mod__operators.