为什么我被困在一个循环中?

Foo*_*Bar -4 c++ loops if-statement while-loop

我根据自己的要求编辑问题,并清楚地表明我的错误.这个问题已得到解答.

为什么我陷入无休止的循环?我尝试了一些不同的技术,比如在if语句中引入break语句,甚至只是在那里抛出break语句.但是我仍然陷入困境.

    while (recalculate = 1){

        cout << "\nEnter in the radius of the sphere: ";
        cin >> radius;
        cout << "\nEnter in the weight of the sphere: ";
        cin >> weight;
        cout << "\n";

        if (bForce > weight)
        {
            cout << "\nEgads, it floats!\n";
        }
        else {
            cout << "\nIt sunk...\n";
        }

        cout << "\nRecalculate? (1 = yes, 0 = exit)\n";
        cin >> recalculate;
        // See what recalculate really is. 
        cout << "\n" << recalculate;

    }
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 6

while(recalculate=1)始终被评估为true,因为1被赋值给,recalculate并且任何不同于零的数值被隐式转换为布尔值true.为了测试相等性,请使用==,即

while(recalculate == 1)

  • @Zachary尝试在构建代码时启用所有编译器警告.例如,用`g ++ -Wall`编译会给你:`警告:建议用作真值的括号括号[-Whatarentheses]`和**不要忽略警告,除非你确定它们是无害的(哪个他们很少) (2认同)