gpt4 book ai didi

c++ - while循环创建无限循环

转载 作者:行者123 更新时间:2023-12-03 06:53:52 25 4
gpt4 key购买 nike

所以我正在为 C++ 类创建一个程序,并且我创建了一个 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;
}

当您希望循环直到满足某些条件时,您需要使用 whileif 就像一个非循环的 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.

关于c++ - while循环创建无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64734077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com