xcode 减少 For 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8024306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 04:09:42  来源:igfitidea点击:

Decrement a For Loop?

xcodefor-loopdecrement

提问by Michael Young

I can increment a FOR loop in xcode, but for some reason the reverse, namely decrementing, doesn't work.

我可以在 xcode 中增加一个 FOR 循环,但由于某种原因,相反的,即递减,不起作用。

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.

我一定是语法错误,但我相信这对于 xcode 中的 Objective C++ 是正确的。

回答by Mark Byers

I think you mean >instead of <:

我认为你的意思是>而不是 <

for (int i = 10; i > 0; --i) {

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 的值与原始代码中的值相同,但顺序相反(即 9, 8, 7, ..., 1, 0),那么您还需要更改边界:

for (int i = 9; i >= 0; --i) {

回答by PackratDragon

I just want to add to keep in mind that --idecrements first, then checks and i--checks, then decrements.

我只想补充一点,请记住,--i先递减,然后检查和 i--检查,然后递减。

回答by Todd

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).

您需要条件为 i>0(如果 i 从 10 开始,则 10<0 为假,因此它永远不会执行循环代码)。

回答by Femaref

You are checking i < 0. This is false in the first iteration and thus the loop isn't executed. Change it to i > 0instead.

你正在检查i < 0。这在第一次迭代中为假,因此不执行循环。改为i > 0改为。

回答by Ted Hopp

Change the termination condition from i<0to i>0

将终止条件从 更改i<0i>0