提问者:小点点

下面代码中的(count=true)/while(count==true)/while(true)有什么区别?


//这里的每个代码在运行时给出不同的答案。 while(true)从0计数到10并停止。 while(count==true)给出了一个数字2并停止,但现在给出了一个数字2的无限循环。 while(count=true)给出一个数字为2的无限循环。

int main()
{
int count = 0;
while (count = true)
{
    count += 1;
    
    if (count > 10)
    {
        break;
    }

    cout << count;
}
}




int main()
{
int count = 0;
while (count == true)
{
    count += 1;
    
    if (count > 10)
    {
        break;
    }

    cout << count;
}
}



int main()
{
int count = 0;
while (true)
{
    count += 1;
    
    if (count > 10)
    {
        break;
    }

    cout << count;
}
}

共1个答案

匿名用户

while (count = true)

在这里,您将true赋值给count并返回它的新值,然后count由于强制转换而变为1并返回1(由于强制转换,当您进行检查时认为true),然后while中的条件保持赋值之前count的任何值。 这相当于while(true)

while (count == true)

这里,您将检查count是否为true,这将为您提供false,因为它等于零,然后您的循环将不会执行。

现在,在第一个循环(将执行)中,count的值将增加到2(由于count+=1),然后它将再次变为1(由于while(count=1)),循环是无止境的,因为count的值无论如何都不会是11,您将在标准输出中看到无限多个2。 而在第二秒,您将看不到任何输出。