What does Console.WriteLine(-7 % 3); print in C#?
Correct answer B. -1
In C#, the result of the remainder operator % takes the sign of the left operand (the dividend). -7 / 3 truncates to -2, and -7 - (-2 × 3) = -1. Some languages such as Python return 2 here because they use floored division, which is why this catches people out. To get a non-negative result, use ((a % n) + n) % n.
Answer checked How we write and check questions
Discussion