❤️C++布尔值❤️

x33g5p2x  于2021-09-24 转载在 C/C++  
字(0.8k)|赞(0)|评价(0)|浏览(376)

布尔值

很多时候,在编程中,您需要一种只能具有两个值之一的数据类型,例如:

  • 是/否
  • 开关
  • 真假
    为此,C++ 有一个bool数据类型,它可以取值true (1) 或false(0)。
    布尔值
    布尔变量是用bool关键字声明的,并且只能取值trueor false:
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. bool cainiao = true;
  5. bool chuan = false;
  6. cout << cainiao << "\n";
  7. cout << chuan;
  8. return 0;
  9. }

演示:

布尔表达式

布尔表达式是一个C ++表达式返回一个布尔值:1(真)或0(假).你可以使用比较运算符,例如大于( >) 运算符来确定表达式(或变量)是否为真:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int x = 25;
  5. int y = 12;
  6. cout << (x > y);
  7. return 0;
  8. }

演示:

或者更简单:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. cout << (10 > 9);
  5. return 0;
  6. }

演示:

在下面的示例中,我们使用等于( ==) 运算符来计算表达式:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int x = 10;
  5. cout << (x == 10);
  6. return 0;
  7. }

演示:

再试试:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. cout << (10 == 15);
  5. return 0;
  6. }

演示:

相关文章

最新文章

更多