对于循环没有在while循环中第二次执行

时间:2012-03-05 17:33:12

标签: c++ for-loop

我只是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;
}

3 个答案:

答案 0 :(得分:2)

您的代码显示未定义的行为。

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

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

在for循环中删除int num1(即for(; num1 <= num2; num1++)之类的内容),然后重试。

答案 1 :(得分:0)

尝试

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

而不是

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

答案 2 :(得分:0)

更改此部分代码

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

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