博客
关于我
C++基础之布尔类型,什么是C++的布尔类型
阅读量:128 次
发布时间:2019-02-26

本文共 1063 字,大约阅读时间需要 3 分钟。

在C语言中,关系运算和逻辑运算的结果只有两种:0 表示假,非 0 表示真。例如:

#include 
int main() { int a, b, flag; scanf("%d %d", &a, &b); flag = a > b; // flag保存关系运算结果 printf("flag = %d\n", flag); return 0;}

运行结果:

10 20flag = 0

C语言并没有彻底从语法上支持“真”和“假”,只是用 0 和非 0 来表示。这一点在 C++ 中得到了改善,C++ 新增了 bool 类型(布尔类型),它一般占用 1 个字节长度。bool 类型只有两个取值,true 和 false:true 表示“真”,false 表示“假”。

bool 是 C++ 中的关键字,其用法和 int、char、long 类似。例如:

#include 
using namespace std;int main() { int a, b; bool flag; // 定义布尔变量 cin >> a >> b; flag = a > b; cout << "flag = "; if (flag) { cout << "true"; } else { cout << "false"; } return 0;}

然而,C++ 中使用 cout 输出 bool 变量的值时仍然是用数字 1 和 0 表示,而不是 true 或 false。Java、PHP、JavaScript 等语言支持布尔类型,但输出结果为 true 或 false。

你也可以使用 true 或 false 显式地对 bool 变量赋值。例如:

#include 
using namespace std;int main() { bool flag = true; if (flag) { cout << "true"; } else { cout << "false"; } return 0;}

运行结果:

true

注意,true 和 false 是 C++ 中的关键字,true 表示“真”,false 表示“假”。

在以后的编码中,我推荐使用 bool 变量来表示逻辑运算、关系运算以及开关变量的值。

转载地址:http://yyvf.baihongyu.com/

你可能感兴趣的文章
python中argparse模块关于 parse_args() 函数详解(全)
查看>>
python中base64编码与解码
查看>>
python中break怎么用_详解Python中break语句的用法
查看>>
python中del函数的垃圾回收
查看>>
Python中DrissionPage的详细解析与实战
查看>>
python中enumerate、变量类型转换
查看>>
python中execute是啥_python – 为什么“c.execute(…)”打破循环?
查看>>
python中exit和break区别_Python中exit()和sys.exit()之间的区别
查看>>
python中h5的用法
查看>>
python中http协议编程_HTTP编程
查看>>
python中if的效率_python中关于if-else使用性能的一点感悟
查看>>
python中import os_Python:相对导入与绝对导入(import)、os.path、__file__
查看>>
python中is和==操作符
查看>>
python中range()函数的返回值是多少?
查看>>
Python中range对象的使用以及打印九九乘法表
查看>>
Python中reshape函数参数-1的意思?
查看>>
Python中set.discard和set.remove方法之间的运行时差异?
查看>>
Python接口自动化测试企业级实战
查看>>
python中tkinter中value_输入字段中的python Tkinter get()值
查看>>
Python中wx.FlexGridSizer
查看>>