Lets take the basic arithmetic operation - modulo
I get different outputs depending on different languages.
Python
>>> -1 % 12
11
C#
var res = -1 % 12;
output: res = -1
Why am I seeing such behaviour? Ideally I'd like the output to be 11 in both cases.
Also does anyone know if I can achieve this in C#?
The premise of the question is incorrect. The %
operator in C# is not the modulus operator, it is the remainder operator, while in Python it is a modulus operator.
As Eric Lippert Describes, modulus and remainder are the same for all positive numbers, but they handle negative numbers differently.
Despite both C# and Python having a %
operator, doesn't mean they both represent a modulus.
It's worth noting that other languages, such as C++ and Java use remainder for the %
operator, not modulus, which likely contributed to why C# choose to use remainder as well. Since there isn't a lot of consistency in what is meant by the %
operator, I would suggest looking it up in the language docs whenever working with a new language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With