2017-02-14 55 views
1

後定點值我目前困惑的while循環,特別是爲什麼循環仍然運行一切在達到定點值特別後的環...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 . . . 

是否有任何方法可以編輯代碼,以便立即退出循環或者這只是所有循環都預先編程的方式?

任何建議,將不勝感激

+0

交換機內部的中斷只打破了交換機,而不是while循環。你應該使用if來測試選項,或者在切換模塊後測試quit。 – Shiping

回答

1

break語句內的開關情況下,僅退出開關塊,而不是while循環外。您的代碼將繼續運行,直到下一次評估while循環條件。