Obj 中奇怪的 mod 行为。 C
我有以下代码:
NSInteger index1 = (stop.timeIndex - 1); //This will be -1
index1 = index1 % [stop.schedule count]; // [stop.schedule count] = 33
所以我有表达式 -1 % 33。这应该给我 32,但实际上给了我 3...我已经仔细检查了调试器中的值。有人有什么想法吗?
I have the following code:
NSInteger index1 = (stop.timeIndex - 1); //This will be -1
index1 = index1 % [stop.schedule count]; // [stop.schedule count] = 33
So I have the expression -1 % 33. This should give me 32, but is instead giving me 3... I've double checked the values in the debugger. Does anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C 语言中,模运算符不适用于负数。 (它给出余数,而不是像其俗名那样进行模运算。)
In C, the modulus operator doesn't work with negative numbers. (It gives a remainder, rather than doing modular arithmetic as its common name suggests.)
C99 在第 6.5.5 节乘法运算符中说(粗体是我的):
它说
%
是余数,并且没有使用“模”这个词来描述它。事实上,“模数”这个词在我的 C99 副本中只出现在三个地方,这些都与库有关,而不是与任何运算符有关。它没有说任何要求余数为正的内容。如果需要正余数,则将
a%b
重写为(a%b + b) % b
将适用于a
的任一符号和b
并给出肯定答案,但需要额外进行加法和除法。将其计算为m=a%b 可能会更便宜; if (m<0) m+=b;
取决于目标架构中丢失的分支或额外的划分是否更便宜。编辑:我对 Objective-C 一无所知。您最初的问题被标记为 C,迄今为止的所有答案都反映了 C 语言,尽管您的示例似乎是 Objective-C 代码。我假设了解 C 的真实情况是有帮助的。
C99 says in Section 6.5.5 Multiplicative operators (bold mine):
It says that
%
is the remainder, and does not use the word "modulus" to describe it. In fact, the word "modulus" only occurs in three places in my copy of C99, and those all relate to the library and not to any operator.It does not say anything that requires that the remainder be positive. If a positive remainder is required, then rewriting
a%b
as(a%b + b) % b
will work for either sign ofa
andb
and give a positive answer at the expense of an extra addition and division. It may be cheaper to compute it asm=a%b; if (m<0) m+=b;
depending on whether missed branches or extra divisions are cheaper in your target architecture.Edit: I know nothing about Objective-C. Your original question was tagged C and all answers to date reflect the C language, although your example appears to be Objective-C code. I'm assuming that knowing what is true about C is helpful.
对负数使用 mod 运算符的结果通常是意想不到的。例如,这个:
用 GCC 产生 -1,但我不明白为什么你期望表达式的计算结果为 32 - 所以它就这样了。通常最好不要执行此类操作,特别是如果您希望代码可移植。
The results of using the mod operator on negative numbers are often unexpected. For example, this:
produces -1 with GCC, but I can't see why you expect the expression to evaluate to 32 - so it goes. It's normally better not to perform such operations, particularly if you want your code to be portable.