while循环创建无限循环

While loop creating infinite loop

所以我正在为 C++ class 创建一个程序,并且我创建了一个 while 循环来停止无效输入。 每次我用无效输入测试它时,它都会进入无限循环。我是编码新手,所以我真的不知道如何解决它。

 cout << "Enter weight in ounces (Max: 1800)" << endl;
    cin >> pkgweight;

    while (pkgweight > 0 || pkgweight < 1800)
    {
        cout << "Weight out of range. Program terminating.\n" << endl;
    }

    cout << "Enter miles shipping (Max: 3500)" << endl;
    cin >> distance;

    while (distance > 0 || distance < 3500)
    {
        cout << "Shipping distance out of range." << endl;
        cout << "Program terminating.\n" << endl;
    }

如果该循环内没有任何变化,则永远不会触发退出条件。

也许你的意思是:

int pkgweight = 0;

cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;

if (pkgweight < 0 || pkgweight > 1800)
{
  cout << "Weight out of range. Program terminating.\n" << endl;
}

您需要使用 while 来处理您想要循环直到满足某些条件的情况。 if 就像 non-looping while.

While it's great that you're learning and it's understood you're going to make mistakes, slipping up on something this fundamental is usually a sign you don't have a good reference to work from. Get yourself a solid C++ reference book and refer to it often if you're ever stumped about something. This is essential for learning properly, not just picking up bits and pieces here and there and trying to intuit the gaps. Many parts of C++ will not make sense, they are artifacts of design decisions decades old and the influence of other programming languages you've never heard of. You need a proper foundation.

如果您希望用户能够更正输入错误,您需要:

 cout << "Enter weight in ounces (Max: 1800)" << endl;
 cin >> pkgweight;

 while (pkgweight > 0 || pkgweight < 1800)
 {
     cout << "Weight out of range. Program terminating.\n" << endl;
     cout << "Enter weight in ounces (Max: 1800)" << endl;
     cin >> pkgweight;
 }

这样,如果用户输入的数字超出有效范围,系统将提示他们输入新数字。如果新值在范围内,循环将退出。

您当前程序的问题是 while 循环将执行“同时”它检查的条件是 true。在您当前的程序中,一旦设置了 pkgweight,它就会保持相同的值。这意味着如果因为它检查的条件是 true 而进入循环,则该条件将永远不会改变(允许循环退出),并且您的错误消息将无限期地打印。

看你的代码,如果输入错误,你似乎想终止程序。您可以考虑终止该功能。 main() 就这些了吗?如果它不在外部函数中,只需执行 return -1。我知道这可能是一种糟糕的编程习惯,但是,嘿,它专门为此工作!
顺便说一句,你的条件说 > 0< 1800,这意味着程序将终止 如果 变量 distance 和 pkgweight 在指定范围内。
这是我没有这些错误的工作片段,在 onlineGDB.

上测试
 #include <iostream>
 using namespace std;
 int main ()
 {
    int pkgweight, distance;
    cout << "Enter weight in ounces (Max: 1800)" << endl;
    cin >> pkgweight;

    while (pkgweight < 0 || pkgweight > 1800)
    {
        cout << "Weight out of range. Program terminating.\n" << endl;
        return -1;
    }

    cout << "Enter miles shipping (Max: 3500)" << endl;
    cin >> distance;

    while (distance < 0 || distance > 3500)
    {
        cout << "Shipping distance out of range." << endl;
        cout << "Program terminating.\n" << endl;
        return -1;
    }
    return 0;
}

当然,除了切换 less-than 和 greater-than,您始终可以将条件语句包装在非运算符中。