减少 For 循环?
我可以在 xcode 中递增 FOR 循环,但由于某种原因,相反的操作(即递减)不起作用。
当然,这种递增工作得很好:
for (int i=0; i<10; ++i) {
NSLog(@"i =%d", i);
}
但是,这种递减不会产生任何结果:
for (int i=10; i<0; --i) {
NSLog(@"i =%d", i);
}
我的语法一定是错误的,但我相信这对于 xcode 中的 Objective C++ 来说是正确的。
I can increment a FOR loop in xcode, but for some reason the reverse, namely decrementing, doesn't work.
This incrementing works fine, of course:
for (int i=0; i<10; ++i) {
NSLog(@"i =%d", i);
}
But, this decrementing doesn't produce a thing:
for (int i=10; i<0; --i) {
NSLog(@"i =%d", i);
}
I must have the syntax wrong, but I believe this is correct for Objective C++ in xcode.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为你的意思是
>
而不是<
:如果你希望 i 的值与原始代码中的值相同,除了相反的顺序(即 9, 8 , 7, ..., 1, 0) 那么您还需要更改边界:
I think you mean
>
instead of<
:If you want the values of i to be the same as in the original code except in reverse order (i.e. 9, 8, 7, ..., 1, 0) then you also need to change the boundaries:
我只是想添加记住
--i
首先递减,然后检查和i--
检查,然后递减。I just want to add to keep in mind that
--i
decrements first, then checks andi--
checks, then decrements.您正在检查
i < 0 。这在第一次迭代中是错误的,因此循环不会被执行。将其更改为
i > 0 代替。
You are checking
i < 0
. This is false in the first iteration and thus the loop isn't executed. Change it toi > 0
instead.您需要条件为 i>0(如果 i 从 10 开始,则 10<0 为 false,因此它永远不会执行循环代码)。
You need the condition to be i>0 (if i starts at 10, then 10<0 is false, so it never executes the loop code).
for (int i = 10; --i >= 0;) {
是在 @Mark Byers 答案中表达 for 循环的一种巧妙方式。
for (int i = 10; --i >= 0;) {
is a neat way to express the for loop in @Mark Byers answer.
将终止条件从
i<0
更改为i>0
Change the termination condition from
i<0
toi>0