c 语言bool 类型数据_C ++中的bool数据类型

c 语言bool 类型数据

In C++ programming language, to deal with the Boolean values – C++ added the feature of the bool data type. A bool variable stores either true (1) or false (0) values.

在C ++编程语言中,为了处理布尔值– C ++添加了bool数据类型的功能 。 布尔变量存储true ( 1 )或false ( 0 )值。

Note that, In C++, true and false are the inbuilt keywords and they represent 1 and 0 respectively.

请注意,在C ++中, true和false是内置关键字,它们分别表示1和0。

So, whenever we need to work with such variables in which we have to store only two values i.e. the variable to hold status like, ON/OFF, YES/NO, TRUE/FALSE, etc we can use bool type variable.

因此,每当需要使用这样的变量时,我们只需要存储两个值即可,即要保持状态的变量,例如ON / OFF,YES / NO,TRUE / FALSE等,我们可以使用bool类型变量

Syntax:

句法:

bool variable_name;

Example 1:

范例1:

#include <iostream>
using namespace std;

int main()
{
    bool var1 = true;
    bool var2 = false;
    bool var3 = 1;
    bool var4 = 0;

    //printing the values
    cout << "var1 : " << var1 << endl;
    cout << "var2 : " << var2 << endl;
    cout << "var3 : " << var3 << endl;
    cout << "var4 : " << var4 << endl;

    return 0;
}

Output:

输出:

var1 : 1
var2 : 0
var3 : 1
var4 : 0

Example 2:

范例2:

#include <iostream>
using namespace std;

int main()
{
    bool status = true;

    if (status)
        cout << "It's true..." << endl;
    else
        cout << "It's false..." << endl;

    status = false;

    if (status)
        cout << "It's true..." << endl;
    else
        cout << "It's false..." << endl;

    return 0;
}

Output:

输出:

It's true...
It's false...

Note: Any non-zero value considers as true and zero considers as false.

注意:任何非零值均视为true零则视为false

Example 3:

范例3:

#include <iostream>
using namespace std;

int main()
{
    bool x = true;

    cout << "x : " << x << endl;

    x = -1;
    cout << "x : " << x << endl;

    x = -123.45f;
    cout << "x : " << x << endl;

    x = "Hello";
    cout << "x : " << x << endl;

    x = 123.456f;
    cout << "x : " << x << endl;

    x = 0;
    cout << "x : " << x << endl;

    x = NULL;
    cout << "x : " << x << endl;

    return 0;
}

Output:

输出:

x : 1
x : 1
x : 1
x : 1
x : 1
x : 0
x : 0

Also read: Use of bool in C language

另请阅读: 在C语言中使用bool

翻译自: https://www.includehelp.com/cpp-tutorial/bool-data-type-in-cpp.aspx

c 语言bool 类型数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值