快速提问。我的"While"循环出现问题
Quick questions. I'm having issues with my "While" loop
我遇到了一个烦人的问题。我遇到的问题是;当我在第一个cin >> statement
输入 -1 时,while 并没有像我想要的那样退出。
我尽量不要在循环中使用"break"
,因为我被告知这是一个坏习惯。
仅供参考,移动On初始化为真。这是代码:
while(moveOn){
cout << "Enter info:";
cin >> weight;
if(weight == -1){
moveOn = false;
}
weight = pack.weight;
cin >> pack.sides[0] >> pack.sides[1] >> pack.sides[2];
while(pack.weight > 0 || pack.sides[0] < 0 || pack.sides[1] < 0 || pack.sides[2] < 0){
cout << "Enter Vaild info:";
cin >> pack.weight >> pack.sides[0] >> pack.sides[1] >> pack.sides[2];
}
girth = getGirth(pack.sides);
float price;
price = getPackageAmount(pack.weight, weights, prices);
cout << price << endl;
if( pack.weight <= 50){
if(pack.sides[0] <= 36 && pack.sides[1] <= 36 && pack.sides[2] <= 36){
if(girth <= 60){
pack.accepted = true;
accepted++;
}
}
}
else{
pack.accepted = false;
rejected++;
}
}
提前谢谢你。
while(moveOn)
并不意味着"当moveOn
变得false
时立即停止" - 测试仅在循环的每次迭代开始时执行。
您需要添加一个else
子句:
while (moveOn)
{
cout << "Enter info:";
cin >> weight;
if(weight == -1){
moveOn = false;
}
else
{
weight = pack.weight;
// ...
}
}
(您可能还希望将weight = pack.weight
更改为pack.weight = weight
。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入