2011-10-09 115 views
0

我有一個while循環,我想逃跑時,我到5While循環逃生範圍

打數1什麼是放了,最好的說法?

我目前有這個。

while ( oneChoice!= 1 || oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5 ) 
{ 
cout << "Please make a selection" << endl; 
cout << "Choose once more: "; 
cin >> oneChoice; 
break; 
} 
+1

爲什麼那裏有'break'? – Griwes

+0

剛剛刪除'break' – 2011-10-09 20:07:16

+0

它在switch語句中的另一個while循環內使用 – mystycs

回答

2

假設oneChoiceint(並因此不能有1和2之間的值,例如),只是改變了條件,以:

while (!(1 <= oneChoice && oneChoice <= 5)) 

或者,等價:

while (oneChoice < 1 || oneChoice > 5) 

此外,如果oneChoice沒有實際意義或重要性befor進入循環時,最好使用do { ... } while (oneChoice < 1 || oneChoice > 5);循環代替。

2
while (oneChoice < 1 or oneChoice > 5) 
{ 
    // 
} 
+0

這意味着只要有任何不在該範圍內的錯誤是正確的?這個範圍內的任何內容都是真的,意味着它會離開? – mystycs

+0

是的。並且不要在循環中使用那個'break'。 – Griwes

+0

我不得不使用break來做一件事。 – mystycs

3

我願意做這樣的:

int n; 
for (;;) 
{ 
    cout << "Please make a selection (1-5): " 
    cin >> n; 
    if (n >= 1 && n <= 5) break; 
    cout << "You must choose a number from 1 through 5.\n"; 
} 

斷裂進入在中間,使得只有當用戶輸入可接受範圍之外的值被印刷在錯誤消息。 for (;;)是適合循環的C族成語,您不希望在頂部或底部測試退出條件。