0

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!^.^

http://www.google.com.hk/#hl=zh-TW&source=hp&q=-1%252&oq=-1%252&aq=f&aqi=&aql=1&gs_sm=e&gs_upl=2572l7521l0l7993l10l10l0l9l0l0l154l154l0.1l1l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=1573ccabb4b5821b&biw=929&bih=825

  • 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 Answers2

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