Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo operator in Objective-C returns the wrong result

I'm a little freaked out by the results I'm getting when I do modulo arithmetic in Objective-C. -1 % 3 is coming out to be -1, which isn't the right answer: according to my understanding, it should be 2. -2 % 3 is coming out to -2, which also isn't right: it should be 1.

Is there another method I should be using besides the % operator to get the correct result?

like image 598
Greg Maletic Avatar asked Mar 12 '10 05:03

Greg Maletic


People also ask

What does modulo operator return in C?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

What are the restrictions of a modulus operator in C?

Exceptional Restrictions of the Modulus Operator in CThe % operator cannot be applied to a set of floating numbers (float or double). The compiler will produce a compile-time error if we try to use this operator with any floating-point variables or even constants in C.

What is the result of mod operator?

Mod is a shortened term for modulus. Mod divides operand1 by operand2 (rounding floating-point numbers to integers) and returns only the remainder as result.


1 Answers

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.

like image 64
Isaac Avatar answered Oct 26 '22 04:10

Isaac