C++:虽然循环次数

问题描述:

所以我想写一个基本程序,要求用户输入除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

嘿路易斯! **欢迎来到* !!! ** ...从你的问题,我会建议你请检查[**此**](http://*.com/questions/388242/the-definitive-c-书籍指南和列表),并至少做两个选择,阅读它们,然后你可以回到这里问你的问题。我们将非常乐意帮助你:-) – WhiZTiM

这是利用

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; 
} 

#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