所以我得到了以下操作:
NSInteger articleIndex = self.featuredArticlesCounter % self.featuredArticles.count;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,self.featuredArticlesCounter为-1,
self.featuredArticles.count为10
所以它基本上是-1%10,应该是9,但结果是5.
谷歌称这是9.
如果我这样做NSInteger articleIndex = -1 % 10;会给我-1
我已经尝试将NSUInteger从count转换为NSInteger,但这不起作用.我试过在所有地方插入括号,但这也不起作用.
我已经切换到使用了((-1 % 10) + 10) % 10.
但我仍然想知道这笔交易是什么.有任何想法吗?
编辑:
featuredArticlesCounter是一个签名的int
self.featuredArticles.count是一个unsigned int
featuredArticlesCounter显然是一个unsigned int.当您认为将其设置为-1时,您确实将其设置为2**32 - 1(~0).那个数字mod 10是5.(显然,2**(8k)-1 % 10是5,所以它实际上是无符号的大小并不重要)
至于为什么-1 % 10是-1的,我相信用C负数的MOD是实现定义的,但在这种情况下(在Java中),它定义成x / y + x % y == x.如果你插入负数,-1 / 10 + -1 % 10 = -1 -> -1 % 10 = -1.