2014-04-09 48 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) { 

} 
相關問題