这个问题在这里已有答案:
FOR命令中的表达式(for(int i = 0; i <([arr count] -1); i ++){}) 3个答案这有效:
int i, start, end; start = m_cardArr.count - 1; end = m_cardArr.count - 4; NSLog(@"%i %i", m_cardArr.count - 1, m_cardArr.count - 4); for(i = start; i > end; i--) { LabyrinthCard* labyCard = (LabyrinthCard*)[m_cardArr objectAtIndex:i]; if(labyCard.m_type != cardType || labyCard.m_usedForDoor) { return false; } }这根本不会进入for循环:
int i; NSLog(@"%i %i", m_cardArr.count - 1, m_cardArr.count - 4); for(i = m_cardArr.count - 1; i > m_cardArr.count - 4; i--) { LabyrinthCard* labyCard = (LabyrinthCard*)[m_cardArr objectAtIndex:i]; if(labyCard.m_type != cardType || labyCard.m_usedForDoor) { return false; } }我没有改变里面数组的大小,所以使用m_cardArr.count作为条件应该可行。 在这两种情况下,当数组中有3个元素时,NSLog会打印2,-1。
我无法弄清楚我在这里缺少什么。
This question already has an answer here:
Expression in FOR command (for (int i=0; i < ([arr count]-1);i++){}) 3 answersThis works:
int i, start, end; start = m_cardArr.count - 1; end = m_cardArr.count - 4; NSLog(@"%i %i", m_cardArr.count - 1, m_cardArr.count - 4); for(i = start; i > end; i--) { LabyrinthCard* labyCard = (LabyrinthCard*)[m_cardArr objectAtIndex:i]; if(labyCard.m_type != cardType || labyCard.m_usedForDoor) { return false; } }This doesn't enter the for loop at all:
int i; NSLog(@"%i %i", m_cardArr.count - 1, m_cardArr.count - 4); for(i = m_cardArr.count - 1; i > m_cardArr.count - 4; i--) { LabyrinthCard* labyCard = (LabyrinthCard*)[m_cardArr objectAtIndex:i]; if(labyCard.m_type != cardType || labyCard.m_usedForDoor) { return false; } }I am not changing the size of the array inside, so using m_cardArr.count as the conditional should work. In both cases, the NSLog prints 2, -1 when there are 3 elements in the array.
I can't figure out what I'm missing here.
最满意答案
这是因为count属性的类型为NSUInteger ,即无符号数。 当你从中减去4并且结果变为负数时,它会被解释为一个非常大的正数。
将结果分配给int ,再次将其重新解释为负数,从而解决问题。
解决这个问题的最佳方法是将-4移动到表达式的另一侧,将符号更改为+ ,如下所示:
for(i = m_cardArr.count - 1; i+4 > m_cardArr.count; i--) { ... }表达式背后的逻辑将保持不变,但您将不再看到减法导致的有符号/无符号副作用。
This is because the count property is of type NSUInteger, i.e. an unsigned number. When you subtract 4 from it and the result becomes negative, it gets interpreted as a very large positive number.
When you assign that result to an int, you re-interpret it as a negative again, fixing the problem.
The best way of addressing this would be moving -4 to the other side of the expression, changing the sign to a +, like this:
for(i = m_cardArr.count - 1; i+4 > m_cardArr.count; i--) { ... }The logic behind the expression would remain the same, but you would no longer see the signed/unsigned side effects caused by subtraction.
更多推荐
发布评论