1
に達した後にセンチネル値に達した後にループはまだ、具体的ループ内で他のすべてを実行し、特に、なぜ私は、whileループで現在混乱しているはループが...センチネル値は
を継続しながら、ここに私の例です以下のコード:
while (quit != -1) {
cout<<"Options: a)ir; w)ater; s)teel; q)uit \n";
char option=' ';
cin>>option;
option = toupper(option);
while(option != 'A' && option != 'W' && option != 'S' && option != 'Q'){
cin.clear();
cout<<"INVALID INPUT!! \n";
cin>>option;
option = toupper(option);
}
switch(option){
case 'Q':
cout<<"You Have Quit!";
quit = -1;
break;
}
cout<<"Please input the distance: \n";
double distance=0;
cin>>distance;
while(distance < 0){
cin.clear();
cout<<"INVALID INPUT \n";
cin>>distance;
}
switch(option){
case 'A':
seconds = distance/speed_a;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
case 'W':
seconds = distance/speed_w;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
case 'S':
seconds = distance/speed_s;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
}
}
ユーザーは、それが終了するswitch文を実行します「Q」の文字を入力する基本的に...それは、ループを終了しないが、それはまだ...
ループを終了する前に移動した距離を要求します出力を以下に示します。
Options: a)ir; w)ater; s)teel; q)uit
q
You Have Quit!
Please input the distance:
0
--------------------------------
Process exited after 2.944 seconds with return value 0
Press any key to continue . . .
コードを編集してすぐにループを終了するようにする方法はありますか?これはすべてのループが事前にプログラムされている方法ですか?
何かアドバイスは、スイッチケース内にbreak文が唯一のスイッチブロックではなく、外側のwhileループを抜ける
スイッチ内のブレークは、スイッチを壊すだけで、whileループはブレークしません。オプションをテストするためにifを使用するか、スイッチブロックの後にテストを終了するかのいずれかを行う必要があります。 – Shiping