为什么我陷入了循环

Why am I Stuck in a Loop?

本文关键字:循环 为什么      更新时间:2023-10-16

我编辑了这个问题,以精确地表达我所问的内容,并清楚地表明我的错误。这个问题已经得到了回答。

为什么我陷入了无休止的循环?我尝试了几种不同的技术,例如在 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;
    }
while(recalculate=1)总是

被计算为true,因为1被分配给recalculate,任何不同于零的数值都被隐式转换为布尔true。要测试相等性,请使用==,即

while(recalculate == 1)

问题是=是一个赋值,而不是一个比较:

if (recalculate = 0) {

上面将recalculate设置为零,然后将其计算为布尔表达式。如果为零,则其计算结果始终为 false,因此永远不会执行if的主体。

编写比较的正确方法是==

if (recalculate == 0) {