❤️C++布尔值❤️

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

布尔值

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

  • 是/否
  • 开关
  • 真假
    为此,C++ 有一个bool数据类型,它可以取值true (1) 或false(0)。
    布尔值
    布尔变量是用bool关键字声明的,并且只能取值trueor false:
#include <iostream>
using namespace std;

int main() {
  bool cainiao = true;
  bool chuan = false;
  cout << cainiao << "\n";
  cout << chuan;
  return 0;
}

演示:

布尔表达式

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

#include <iostream>
using namespace std;

int main() {
  int x = 25;
  int y = 12;
  cout << (x > y);
  return 0;
}

演示:

或者更简单:

#include <iostream>
using namespace std;

int main() {
  cout << (10 > 9);
  return 0;
}

演示:

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

#include <iostream>
using namespace std;

int main() {
  int x = 10;
  cout << (x == 10);
  return 0;
}

演示:

再试试:

#include <iostream>
using namespace std;

int main() {
  cout << (10 == 15);
  return 0;
}

演示:

相关文章

微信公众号

最新文章

更多