2014-04-09 44 views
0

我在for循环内有大量的代码。我想根据布尔变量countUp执行0到9递增或9到0递减的循环。设置初始条件和增量很容易...但是如何以编程方式设置条件(操作员是问题)?我可以以编程方式在`for`循环中设置条件吗?

int startValue = _countUp ? 0 : 9; 
int increment = _countUp ? 1 : -1; 
// How do I define a condition ??? so that the following single line of code will work: 

for (int i = startValue; ???; i = i + increment) { 
    ... 

我试过一个NSString,这当然没有工作。我知道有些解决方案将两个循环放在一个if-else语句中,即将循环代码定义为一个函数,并使用升序或降序for循环来调用它。但有没有一种优雅的方式来设置for循环编程?

+0

多个很好的答案在这里;希望我可以信任多个。我最终会实现Bryan的第二个解决方案,但是RobP遇到了关于有条件地定义条件的主要问题。 – Henry95

回答

1

如何有关使用三元运算符?它简洁明了,应该做到这一点。

for(int i = startValue; _countUp ? (i <= 9) : (i >=0); i = i + increment) { 
+0

+1用于直接回答问题,并使用OP询问的正确运算符。 – Milo

+0

谢谢,就是这样。出于好奇,什么类型的变量是(我<= 9)?如果我想独立于'for'语句来定义它,该怎么办? – Henry95

+0

它是布尔值,是一个真值或假值。任何'if()'的()中的条件需要评估为一个布尔值,并且A中的条件在'A? B:C'也需要评估为布尔值。 – RobP

4

的一种方式是添加了endValue

int startValue = _countUp ? 0 : 9; 
int increment = _countUp ? 1 : -1; 
int endValue = _countUp ? 9 : 0; 

for (int i = startValue; i != endValue; i = i + increment) { 

} 

或eaiser

for (int i = 0; i < 10; i++) { 
    int value = _countUp ? i : 9 - i; 
    // use value 
} 
0

我只是在for循环中实现三元运算符。

for (int i = _countUp ? 0 : 9; i != _countUp ? 9 : 0; i += _countUp ? 1 : -1) { 

} 
相关问题