困惑于以下代码

时间:2013-12-16 22:32:35

标签: c++ configuration

所以我目前正在学习如何使用C ++进行编码。我在下面看到了以下代码。

    // =======================
    // Lesson 2.4.3 - Do while
    // =======================

    #include<iostream>
    using namespace std;

    int main()
    {
        bool condition = false;

        do
        {
        cout << "Enter a 0 to quit or 1 to continue: ";
        cin >> condition;
        }

        while (condition);
    }

为什么C ++自动知道0打破了循环并且1继续循环?知道0 = false并且上面的任何内容都是真的,它是否与命令有关? 感谢那些可以提供帮助的人。

5 个答案:

答案 0 :(得分:2)

这就是布尔逻辑的工作原理。 0为假,任何非0都为真。

答案 1 :(得分:1)

这是因为while(0)的计算结果为false,因此终止了循环。

答案 2 :(得分:1)

变量condition的类型为bool,因此其值可以是truefalse。当它为假时,循环终止。在bool的输入和输出上,0为假,1为真。

答案 3 :(得分:0)

bool变量可以有两个条件,即true或false。 0被认为是假,0以外的任何值都被认为是真。所以你写的条件是(当condition = true时。

while(!0) // body opf while will execute

当条件= false时,c ++会像这样解释它

while(0)  // and body of do while will not execute.

答案 4 :(得分:-1)

因为在读取输入后,将检查条件while (condition);

while (condition = true);

默认情况下,第一个代码设置为上面的

这意味着do while循环体中的代码将在条件值为true时循环(1)

相关问题