Today I was writing a program in C#, and I used % to calculate some index... My program didn't work, so I debugged it and I realized that "%" is not working like in other program languages that I know.
For example:
In Python %
returns values like this:
for x in xrange (-5, 6): print x, "% 5 =", x % 5 -5 % 5 = 0 -4 % 5 = 1 -3 % 5 = 2 -2 % 5 = 3 -1 % 5 = 4 0 % 5 = 0 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4 5 % 5 = 0
In C#:
for (int i = -5; i < 6; i++) { Console.WriteLine(i + " % 5 = " + i % 5); } -5 % 5 = 0 -4 % 5 = -4 -3 % 5 = -3 -2 % 5 = -2 -1 % 5 = -1 0 % 5 = 0 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4 5 % 5 = 0
Did I do something wrong or is %
not working like it should?
Modulo is a math operation that finds the remainder when one integer is divided by another. In writing, it is frequently abbreviated as mod, or represented by the symbol %. Where a is the dividend, b is the divisor (or modulus), and r is the remainder.
How to Do a Modulo Calculation. The modulo operation finds the remainder of a divided by b. To do this by hand just divide two numbers and note the remainder. If you needed to find 27 mod 6, divide 27 by 6.
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).
The MOD Function[1] is categorized under Excel Math and Trigonometry functions. The function helps find a remainder after a number (dividend) is divided by another number (divisor). As a financial analyst, the function is useful when we need to process every nth value.
As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the %
operator.
You ask:
How can I use modulus operator in C#?
You can define a modulus operator yourself that behaves the same way as the Python %
operator:
int mod(int a, int n) { int result = a % n; if ((result<0 && n>0) || (result>0 && n<0)) { result += n; } return result; }
Both answers are correct. Although personally I think the "always positive" one makes more sense.
You can define your own modulus function that only gives positive answers like this:
int mod(int a, int n) { return ((a%n)+n) % n; }
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