C++ 逻辑运算符
3.4 逻辑运算符
作用:用于根据表达式的值返回真值或假值
逻辑运算符有以下符号:
| 运算符 | 术语 | 示例 | 结果 |
|---|---|---|---|
| ! | 非 | !a | 如果a为假,则!a为真;如果a为真,则!a为假。 |
| && | 与 | a && b | 如果a和b都为真,则结果为真,否则为假 |
| || | 或 | a || b | 如果a和b有一个为真,则结果为真,二者都为假时,结果为假。 |
示例1:逻辑非
// 逻辑运算符 非
#include <iostream>
using namespace std;
int main() {
// 逻辑运算符 非 !
int a = 10;
// 在 C++ 中,除了0都为真
cout << !a << endl; // 0
cout << !!a << endl; // 1
system("pause");
return 0;
}
示例2:逻辑与
// 逻辑运算符 与
#include <iostream>
using namespace std;
int main() {
// 逻辑运算符 - 与 &&
int a = 10;
int b = 10;
cout << (a && b) << endl; // 1
a = 0;
b = 10;
cout << (a && b) << endl; // 0
a = 0;
b = 0;
cout << (a && b) << endl; // 0
// 同真为真,其余为假
system("pause");
return 0;
}
总结:逻辑与运算符总结:同真为真,其余为假
示例3:逻辑或
// 逻辑运算符 --- 或
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 10;
cout << (a || b) << endl; // 1
a = 0;
b = 10;
cout << (a || b) << endl; // 1
a = 0;
b = 0;
cout << (a || b) << endl; // 0
// 逻辑或:同假为假,其余为真
system("pause");
return 0;
}
逻辑或运算符总结:同假为假,其余为真

浙公网安备 33010602011771号