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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With