C++ Modulus Operator weirdness
Its surprising that the modulus (%) operator in C++ works upwards, but not downwards. When working on some code, I expected,
-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
but ended up with,
-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
As a result, you’d need to ensure that either you check that your result is <0 and reset it accordingly,
result = n % 3;
if( result < 0 ) result += 3;
Or, a better solution might be to change the expression such that the negative case never arises,
{ int n = 0; int inc = -1; cout << (20 + n + inc) % 10; }
9
{ int n = 9; int inc = 1; cout << (20 + n + inc) % 10; }
0
Hope this helps someone out there!