在一个程序中使用for、while、do-while循环

Using for, while, do-while loops in one program

本文关键字:for while 循环 do-while 程序 一个      更新时间:2023-10-16

这个程序应该得到用户输入的任何数字(x)的倍数,直到它达到(y)。所有三个循环都正确运行,但是当一起使用时,我们得到了前两个循环,但第三个循环没有输出。我还想在新的一行中输出每个循环的输出。我的问题是我能做些什么来让我的输出在三个单独的行中,为什么我的第三个循环没有输出任何东西。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool error(const string & msg);
int main(){
    unsigned x, y;
    cout << "Give me a number you want the multiples of and give me the max limit: ";
    cin >> x >> y || error("Input Failure: ");
    if (x == 0) error("Input can't be 0");
    unsigned increment = x;
    x = 0;
   while( x < y)
   {
       cout << x << ", ";
       x += increment;
       if (x > y) break;
}
    cout << endl; // This was the other problem. I kept putting it inside the loop 
    for(int x; x < y; x += increment){
        cout << x << ", ";
        if (x > y) break;
    }
    cout << endl; // This was the other problem. I kept putting it inside the loop 
    x = 0; // This is what originally was wrong 
    do{
        cout << x << ", ";
        x += increment;
        if ( x > y){
            break;
        }
    }while (x < y);
}
bool error(const string & msg){
        cout <<"Fatal error: " << msg << endl;
        exit(EXIT_FAILURE);
}

这并不奇怪。当您单独运行第三个循环时,变量x不会被其他两个循环修改。实际上,第三个循环正在执行。第一个循环输出0,5,…, 35,然后第二个循环打印0,5,…, 35(注意

 unsigned increment = x;
x = 0;
while( x < y)
{
   cout << x << ", ";
   x += increment;
   if (x > y) break;
}
for(x = 0; x < y; x += increment){
    cout << x << ", ";
    if (x > y) break;
}
 x=0;
do{
    cout << x << ", ";
    x += increment;
    if ( x > y){
        break;
    }
}while (x < y);

for循环不会输出,因为您重新定义了x并且没有给它一个新值。我不确定为什么你使用三个循环,实际上做同样的事情,除非你只是好奇他们是如何工作的。例如,你可以这样做,用不同的循环输出相同的内容:

#include <iostream>
using namespace std;
int main()
{
    unsigned counter, increment, limit;
    cout << "Give me a number you want to increment by of and give me the max limit: ";
    cin >> increment >> limit;
    //Check to see if the input stream failed
    if(cin.fail())
    {
        cout << "Fatal Error: Input Failure" << endl;
        return -1;
    }
    if(increment == 0 || limit == 0)
    {
        cout << "Input Cannot Be 0" << endl;
        return -1;
    }
    if(limit <= increment)
    {
        cout << "Limit <= Increment" << endl;
        return -1;
    }
    cout << "First Loop" << endl;
    counter = 0; //Set counter to 0 for 1st loop
    while(counter <= limit)
    {
        cout << counter << ", ";
        counter += increment;
    }
    cout << endl;
    cout << "Second Loop" << endl;
    //for loop resets counter for 2nd loop
    for(counter = 0; counter <= limit; counter += increment)
    {
        cout << counter << ", ";
    }
    cout << endl;
    cout << "Third Loop" << endl;
    //Reset counter again for 3rd loop
    counter = 0;
    do{
        cout << counter << ", ";
        counter += increment;
    }while (counter <= limit);
    return 0;
}