I search in google with -1%2 is (-1) mod 2 = 1, but in xcode -1%2= -1. Have any one tell me why? Thank your help!^.^
Asked
Active
Viewed 145 times
0
-
possible duplicate of [Modulo operator in Objective-C returns the wrong result](http://stackoverflow.com/questions/2430737/modulo-operator-in-objective-c-returns-the-wrong-result) – Caleb Oct 22 '11 at 06:43
2 Answers
3
This text was taken from this post.
Objective-C is a superset of C99 and C99 defines a % b
to be negative when a
is negative. See also the Wikipedia entry on the Modulo operation and this StackOverflow question.
Something like (a >= 0) ? (a % b) : ((a % b) + b)
(which hasn't been tested and probably has unnecessary parentheses) should give you the result you want.

Community
- 1
- 1

OmnipotentEntity
- 16,531
- 6
- 62
- 96
-
+1 for link to other SO question. Of interest to those looking into the difference between modulo and remainder: http://codewiki.wikispaces.com/mod+and+rem – Ray Toal Oct 22 '11 at 05:50
2
Often, the modulo operator is calculated using:
number % modulus := number - (number / modulus) * modulus
In your case, you get (-1) - (-1/2)*2 = (-1) - (0) = -1
. Note that the -1/2 evaluates to 0 since we are using integar math.
It is beyond me if all computers operate this way, or if it varies depending on the hardware, but I remember this coming up in a class years ago.

Andrew_L
- 3,021
- 2
- 19
- 18