coneybeare coneybeare - 4 months ago 23
Objective-C Question

Weird Objective-C Mod Behavior for Negative Numbers

So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c

I expect this:

-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2


But get this

-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2


Why is this and is there a workaround?

Answer
result = n % 3;
if( result < 0 ) result += 3;

Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.

Comments