2016-08-03 174 views
-5

所以我想寫一個基本程序,要求用戶輸入除5以外的任何數字,並且在10次迭代用戶未輸入數字5之後,我希望程序打印向屏幕。 這裏是我到目前爲止的代碼:C++:雖然循環次數

#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 

    int num; 

    cout << "Please enter a number other than 5." << endl; 
    cin >> num; 

    while (num != 5){ 
     cout << "Please enter a number other than 5." << endl; 
     cin >> num; 
    } 

    return 0; 
} 

我只是不知道如何告訴計算機停止在10次迭代循環並輸出到屏幕上。

+3

跟蹤計數器.. – Li357

+0

如果用戶在while循環中輸入5,會發生什麼情況? –

+0

嘿路易斯! **歡迎來到Stackoverflow !!! ** ...從你的問題,我會建議你請檢查[**此**](http://stackoverflow.com/questions/388242/the-definitive-c-書籍指南和列表),並至少做兩個選擇,閱讀它們,然後你可以回到這裏問你的問題。我們將非常樂意幫助你:-) – WhiZTiM

回答

1

這是利用

do while 

它的工作原理是,將塊內執行該語句的方式,而不評估任何條件,然後評估條件,以合適的時間確定循環是否應該再次運行

這是您的程序可能看起來像

#include <iostream> 
using namespace std; 

int main(void) 
{ 
int counter = 0, num; 
do 
{ 
if (counter > 10) // or >=10 if you want to display if it is 10 
{ 
cout << "exiting the loop!" << endl; 
break; // the break statement will just break out of the loop 
} 
cout << "please enter a number not equal to 5" << endl; 
cin >> num; 
counter++; // or ++counter doesn't matter in this context 

} 
while (num != 5); 
return 0; 
} 
-2
#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 

    int num; 
    int counter=1; 

    cin >> num; 
    cout <<num; 
    if(num==5) 
    cout << "Please enter a number other than 5." << endl; 



    while (num != 5&&counter<=10){ 
     cin >> num; 
     cout <<num; 
     if(num==5) 
     cout << "Please enter a number other than 5." << endl; 
     counter=counter+1; 
    } 

    return 0; 
} 
+0

如果用戶首先輸入5,程序不起作用 –

+0

雅這就是他要求....如果用戶輸入5,然後他需要退出循環 – rUCHit31