WTF? Xcode can't do modulus correctly?

Member
Posts: 43
Joined: 2009.10
Post: #1
So this doesn't make any sense to me. I have integers and this equation:

int index = (val - 2) % n

Debugging reveals that n is 9, val is 1. So this should equate to:

int index = (1 - 2) % 9

which is:

-1 % 9

which in every other language I've used would give a value of 8. Xcode says it returns a value of -1. What gives?
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Sage
Posts: 1,482
Joined: 2002.09
Post: #3
You'll also find that integer division for negative numbers doesn't give the same result either. Annoying perhaps that they are different, but both are mathematically sound as long as (a/b)*b + a%b = a.

http://en.wikipedia.org/wiki/Modulo_operation for more information if you want to see how much of a mess this really is between different languages. Previous to C99, compilers could even choose how they wanted to define it based on what was easiest or made the most sense given what the hardware used. This is very frustrating for cross platform code.

Scott Lembcke - Howling Moon Software
Author of Chipmunk Physics - A fast and simple rigid body physics library in C.
Quote this message in a reply
Member
Posts: 43
Joined: 2009.10
Post: #4
Thanks guys.
Quote this message in a reply
Post Reply