如何在 C++ 中将 do while 循环转换为 while 循环?

问题描述

我编写了一个 C++ 程序,让用户使用 do while 循环输入正数。尽管如此,当我尝试将 do while 循环转换为 while 循环时,预期输出do while 循环不同。代码如下:

#include <iostream>
using namespace std;

int main()
{
    int n;

    do
    {
        cout << "Enter a non-negative integer: ";
        cin >> n;
        if (n < 0)
        {
            cout << "The integer you entered is negative. " << endl;
        }

    }
    while (n < 0);

    return 0;
}

终端要求用户重新输入数字,直到我编写的上述代码为正。但是,我尝试将 do while 循环转换为 while 循环,如下所示,根本没有输出

我可以知道我写错了哪一部分吗?谢谢。

#include <iostream>
using namespace std;

int main()
{
    int n;

    while (n < 0)
    {
        cout << "Enter a non-negative integer: ";
        cin >> n;
        if (n < 0){
            cout << "The integer you entered is negative. " << endl;
         }
    }

    return 0;
}

解决方法

在您的代码的 while 版本中,您不知道什么是 n,因为它在您在 while (n<0) 中使用之前没有被初始化。

int main()
{
    int n;
    // HERE YOU DO NOT KNOW IF n is NEGATIVE OR POSITIVE,YOU EITHER NEED TO INITIALIZE IT OR
    // ENTER IT by cin >> n
    while (n < 0)
    {
        cout << "Enter a non-negative integer: ";
        cin >> n;
        if (n < 0){
            cout << "The integer you entered is negative. " << endl;
         }
    }

    return 0;
}

然后您需要稍微重新排列以获得相同的输出以及使用循环外的 n 的第一个输入。

例如,这将提供相同的输出:

#include <iostream>
using namespace std;

int main()
{
    int n=-1;
    cout << "Enter a non-negative integer: ";
    cin >> n;
    while (n < 0)
    {

        if (n < 0)
        {
            cout << "The integer you entered is negative. " << endl;
            cout << "Enter a non-negative integer: ";
            cin >> n;
        }
        else
        {
            // if positive you get out of the loop
            break;
        }
 
    }

    return 0;
}

,

你必须在while(n

#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "Enter a non-negative integer: ";
    cin >> n;
    while (n < 0)
    {
        cout << "Enter a non-negative integer: ";
        cin >> n;
    if (n < 0)
            cout << "The integer you entered is "
                 << "negative. " << endl;
    }
    
    return 0;
}

或者你可以用负数初始化它:

#include <iostream>
using namespace std;

int main()
{
    int n=-1;
    
    while (n < 0)
    {
        cout << "Enter a non-negative integer: ";
        cin >> n;
    if (n < 0)
            cout << "The integer you entered is "
                 << "negative. " << endl;
    }
    
    return 0;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...