问题描述
当我在Objective-C中进行模运算时,我对获得的结果感到有些惊讶. -1%3得出的结果是-1,这不是正确的答案:根据我的理解,应该是2.-2%3得出的结果是-2,这也不正确:应该是1.
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?
推荐答案
Objective-C是C99的超集,当a
为负数时,C99将a % b
定义为负数.另请参见有关Modulo操作的Wikipedia条目和.
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.
(a >= 0) ? (a % b) : ((a % b) + b)
之类的东西(未经测试,可能带有不必要的括号)应该可以为您提供所需的结果.
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.
这篇关于Objective-C中的模运算符返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!