【问题标题】:C++: While Looping Amount of TimesC ++:循环次数
【发布时间】:2016-08-03 04:01:58
【问题描述】:

所以我正在尝试编写一个基本程序,要求用户输入除 5 以外的任何数字,并且在用户不输入数字 5 的 10 次迭代之后,我希望程序打印到屏幕上。 到目前为止,这是我的代码:

#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 次迭代时停止循环并输出到屏幕。

【问题讨论】:

  • 用计数器跟踪..
  • 如果用户在while循环中输入5会发生什么?
  • 嘿路易斯! 欢迎来到 Stackoverflow !!! ...根据您的问题,我建议您检查 this 并至少选择两个选项,阅读它们,然后您可以回到这里询问您的问题..我们很乐意为您提供帮助:-)

标签: c++ loops while-loop


【解决方案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;
    }
    

    【讨论】:

    • 是的,这就是他的要求....如果用户输入 5,那么他需要退出循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多