在 C 语言 中,没有 bool 类型,因此关系运算和逻辑运算的结果用 0 表示假,用非 0 表示真,在 C++ 中,增加了 bool 类型,用 true 来表示真,用 false 来表示假。
bool varname;
参数 | 描述 |
---|---|
bool | 定义布尔类型变量使用的关键字。 |
varname | 变量名。 |
我们定义了一个 bool 类型的 变量 varname。
C++ 中 bool 类型,表示真假
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
int score = 0;
bool isPass;
cout << "请输入成绩: ";
cin >> score;
if (score >= 60)
{
isPass = true;
}
else
{
isPass = false;
}
if (isPass == true)
{
cout << "Do a good job!" << endl;
}
else
{
cout << "Come on!" << endl;
}
return 0;
}
程序运行后,控制台输出如下:
我们首先,定义了一个 int 类型 的变量 score,并接着,使用了 cin 输入了变量 score 的值,接着,我们使用了 if 判断,如果 score 大于等于 60,那么就将布尔变量 isPass 设置为 true,否则,设置为 false。
最后,我们再次使用 if 判断如果 isPass 是 true,则输出一句话,否则,输出另一句话。
C++ 中 bool 变量 true 表示真,false 表示假
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
int num1 = 0;
int num2 = 0;
bool num1GreateNum2;
cout << "请输入 num1: ";
cin >> num1;
cout << "请输入 num2: ";
cin >> num2;
num1GreateNum2 = num1 > num2;
if (num1GreateNum2 == true)
{
cout << "Num1 is greate than num2" << endl;
}
else
{
cout << "Num1 is less than num2" << endl;
}
return 0;
}
程序运行后,控制台输出如下:
我们将 num1 和 num2 的比较结果,赋值给了 bool 变量 num1GreateNum2,结果,我们可以看到,如果结果为真,那么 num1GreateNum2 的值为 true,否则,num1GreateNum2 的值为 false。
在 C++ 中,增加了 bool 类型,用 true 来表示真,用 false 来表示假。