2.6 布尔值

原文来自:http://www.learncpp.com/cpp-tutorial/26-boolean-values/

布尔值只有两个可能的值:true(1)和false(0).

用bool进行声明:

   1: bool bValue;

 

有两种方式进行赋值:

   1: bool bValue1 = true; // explicit assignment
   2: bool bValue2(false); // implicit assignment

 

正如操作符-能够使得一个正数变成一个负数,逻辑操作符!能够将布尔型值取相反的一个。

   1:  
   2:  bValue1 = !true; // bValue1 will have the value false
   3:  bValue2(!false); // bValue2 will have the value true

 

布尔型变量并不被解释为true或false,而是0或1.因此,当输出一个布尔型变量时,false的值输出0,true的值输出1.

 

   1: bool bValue = true;
   2: cout << bValue << endl;
   3: cout << !bValue << endl;
   4:  
   5: bool bValue2 = false;
   6: cout << bValue2 << endl;
   7: cout << !bValue2 << endl;

 

输出:

1
0
0
1

布尔变量最常用在if语句中。

   1: bool bValue = true;
   2: if (bValue)
   3:     cout << "bValue was true" << endl;
   4: else
   5:     cout << "bValue was false" << endl;

输出

bValue was true

同样:

   1: bool bValue = true;
   2: if (!bValue)
   3:     cout << "The if statement was true" << endl;
   4: else
   5:     cout << "The if statement was false" << endl;

结果:

The if statement was false

用布尔型变量来作为函数的返回值也是很有用的,能够检测一些东西是否正确。如:

   1: #include <iostream>
   2:  
   3: using namespace std;
   4:  
   5: // returns true if x and y are equal
   6: bool IsEqual(int x, int y)
   7: {
   8:     return (x == y); // use equality operator to test if equal
   9: }
  10:  
  11: int main()
  12: {
  13:     cout << "Enter a value: ";
  14:     int x;
  15:     cin >> x;
  16:  
  17:     cout << "Enter another value: ";
  18:     int y;
  19:     cin >> y;
  20:  
  21:     bool bEqual = IsEqual(x, y);
  22:     if (bEqual)
  23:         cout << x << " and " << y << " are equal"<<endl;
  24:     else
  25:         cout << x << " and " << y << " are not equal"<<endl;
  26:     return 0;
  27: }

 

 

我们也可以直接在if语句判断体中调用函数。

   1: if (IsEqual(x, y))
   2:     cout << x << " and " << y << " are equal"<<endl;
   3: else
   4:     cout << x << " and " << y << " are not equal"<<endl;

当将整型变量转变成布尔型时,0被解释为false,非零值被解释为true。

posted @ 2012-05-06 23:34  grassofsky  阅读(309)  评论(0编辑  收藏  举报