【问题标题】:For loop not being executed second time around in a while loop在while循环中没有第二次执行for循环
【发布时间】:2012-03-05 17:33:12
【问题描述】:

我只是 C++ 的初学者。我正在编写一个小而简单的程序,它在两个用户指定的整数之间打印一系列整数。

最后,如果用户返回 1,程序将重新运行 while 循环,但是当这种情况发生时,程序将不会再次打印这一系列数字(for 循环不起作用)。

这里是源代码:

int main(void)
{
    int num1, num2;
    int doContinue = 1;

    while (doContinue == 1)
    {
        cout << "Please enter two integers, the first being the smallest: ";

         do { //does everything in curly braces while the user inputs the numbers wrong...
                cin >> num1 >> num2;

                if (num1 > num2)
                    {
                        cout << "Your first number was bigger than the second.\nTry again!: ";
                    }

            } while (num1 > num2);//... but once it's not wrong, break out of this do loop

        //at this point the input has been checked, so we can proceed to print the series

        for(int num1; num1 <= num2; num1++)
            {   
                cout << num1 << " \n";
            }

        cout << "Would you like to compute another series of integers? 1=yes, anything else=no: ";
        cin >> doContinue;
    }

    return 0;
}

【问题讨论】:

    标签: c++ for-loop


    【解决方案1】:

    您的代码表现出未定义的行为。

        for(int num1; num1 <= num2; num1++)
            {   
                cout << num1 << " \n";
            }
    

    创建一个名为num1 的新整数,与for 循环外的num1 无关。您没有初始化num1 的值,而是继续对其进行比较。

    删除 for 循环中的 int num1(即 for(; num1 &lt;= num2; num1++) 之类的东西),然后重试。

    【讨论】:

    • 这解决了我的问题,谢谢!我将其更改为: for(; num1
    【解决方案2】:

    试试

    for(int i = num1; i<= num2; i++)
    

    而不是

    for(int num1; num1 <= num2; num1++)
    

    【讨论】:

    • 感谢您的回复 :) 我之前尝试过,但出现编译器错误:警告:语句无效。
    • @BillyONEal 为什么它不能那样工作?如果他打印i
    • @talnicolas:因为您更改了 OP 代码的语义。固执地他正在寻找他的num1 在循环执行后进行更改,而您的修改(复制)并没有这样做。即使num1 在使用后被丢弃,你也浪费了一个变量来复制一个无论如何都将被销毁的值。出于某种原因,for 循环的第一个子句是可选的。
    • @BillyONeal 没有注意到他想要更改num1,他只是指定他需要打印一个值范围。不过没问题,祝你有美好的一天。
    • 事实上,我更喜欢这个答案。因为,它不会改变 num1 的值。通过查看 OP 的代码,num1 是否更改无关紧要......
    【解决方案3】:

    修改这部分代码

    for(int num1; num1 <= num2; num1++)
                {   
                    cout << num1 << " \n";
                }
    

    for( ; num1 <= num2; num1++)
                {   
                    cout << num1 << " \n";
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多