Wolfy Wolfy - 7 days ago 7
C# Question

% (mod) explanation

Today I was writing an program in C# and I used % to calculate some index... my program did't work so I debuged 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


My question is:

Did I done something wrong or % is not working like it should?

Answer

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 was as the Python % operator:

int mod(int a, int n)
{
    int result = a % n;
    if ((a<0 && n>0) || (a>0 && n<0))
        result += n;
    return result;
}