为什么嵌套的while循环无限循环?

时间:2020-11-04 06:22:58

标签: c++

我很难让这个嵌套的while循环发挥我想要的功能。

#include <iostream>
#include <math.h>

double time_to_ground(double);

int main() {
    std::cout.precision(4);
    bool go = 1;
    double height{};
    while (go) {
        std::cout << "Please enter the height of the building in meters.\n";
        std::cin >> height;
        while (height < 0) {
            std::cout << "\nPlease enter a positive number.\n";
            std::cin >> height;
        }
        double time = time_to_ground(height);
        std::cout << "It will take " << time << " seconds for the ball to reach the ground to reach the ground.\n";
        std::cout << "Go again?\n0) no\n1) yes\n";
        std::cin >> go;
        //This loop breaks the code
        while (!((go == 0) || (go == 1))) {
            std::cout << "Enter either:\n0) no\n1) yes\n";
            std::cin >> go;
        }   
    }
    return 0;
}

double time_to_ground(double height) {
    return sqrt(2 * height / 9.81);

}

这个想法只是为了确保用户仅输入0或1。如果我输入0或1,它就可以正常工作。但是,当我运行代码并输入“ 6”时,我陷入了无限大的困境。循环!

谢谢!

3 个答案:

答案 0 :(得分:2)

您已将go声明为bool,但是您试图将其读取为整数。

只需将bool go = 1;更改为int go = 1;

尝试将非01的整数输入读入布尔变量失败,并且一旦cin失败,所有使用cin的输入将失败,直到您清除错误。这就是为什么您会遇到无限循环的原因。

编写循环的另一种方法是直接检查输入错误。您可以将go变量保留为bool并将其写为

    while (!(std::cin >> go))
    {
        std::cin.clear(); // clear the cin error
        std::cout << "Enter either:\n0) no\n1) yes\n";
    }

之所以可行,是因为如果输入失败,std::cin >> go将返回false。请注意,一旦发生错误,我就会清除。

答案 1 :(得分:0)

对此的另一种解决方案是保留bool go = 1;,然后替换:

while (!((go == 0) || (go == 1))) {
            std::cout << "Enter either:\n0) no\n1) yes\n";
            std::cin >> go;
        }

具有:

while (std::cin.fail())
        {
            std::cin.clear(); 
            std::cout << "Enter either:\n0) no\n1) yes\n";
            std::cin >> go;
        }
    如果最后一个std::cin.fail()输入失败,则
  • std::cin返回 true 。但是否则将返回 false

  • std::cin.clear()清除std::cin上的错误标志。

答案 2 :(得分:0)

在主函数中使用int数据类型

int go = 1;

代替bool

bool go = 1;

布尔不能处理除0,1以外的值 它会起作用。