天天看點

C++布爾值

文章目錄

布爾值 布爾表達式

很多時候,在程式設計中,您需要一種隻能具有兩個值之一的資料類型,例如:

  • 是/否
  • 開關
  • 真假

為此,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++布爾值

布爾表達式是一個C ++表達式傳回一個布爾值:1(真)或0(假).你可以使用比較運算符,例如大于( >) 運算符來确定表達式(或變量)是否為真:

#include <iostream>
using namespace std;

int main() {
  int x = 25;
  int y = 12;
  cout << (x > y);
  return 0;
}      
C++布爾值

或者更簡單:

#include <iostream>
using namespace std;

int main() {
  cout << (10 > 9);
  return 0;
}      
C++布爾值

在下面的示例中,我們使用等于( ==) 運算符來計算表達式:

#include <iostream>
using namespace std;

int main() {
  int x = 10;
  cout << (x == 10);
  return 0;
}
      
C++布爾值

再試試:

#include <iostream>
using namespace std;

int main() {
  cout << (10 == 15);
  return 0;
}
      
C++布爾值

繼續閱讀