一、算术运算符
处理四则运算
#include <iostream> using namespace std; int main() { //算数运算 int a1 = 10; int b1 = 3; cout << "a1=" << a1 << endl; cout << "b1=" << b1 << endl; cout << "a1 + b1=" << a1 + b1 << endl; cout << "a1 - b1=" << a1 - b1 << endl; cout << "a1 * b1=" << a1 * b1 << endl; cout << "a1 / b1=" << a1 / b1 << endl; cout << "a1 % b1=" << a1 % b1 << endl; cout << "a1++ " << a1++ << endl; //先输出,后运算++ cout << " a1-- " << a1-- << endl;//先输出,后运算-- cout << "++a1 " << ++a1 << endl;//先运算,后输出 cout << "--a1 " << --a1 << endl;//先运算,后输出 return 0; }
a1=10 b1=3 a1 + b1=13 a1 - b1=7 a1 * b1=30 a1 / b1=3 a1 % b1=1 a1++ 10 a1-- 11 ++a1 11 --a1 10
二、赋值运算符
将表达式的值赋值给变量
#include <iostream> using namespace std; int main() { //赋值预算 int a = 2; a += 2; cout << "a += 2 的结果" << a << endl; a -= 2; cout << "a -= 2 的结果" << a << endl; a *= 2; cout << "a *= 2 的结果" << a << endl; a /= 2; cout << "a /= 2 的结果" << a << endl; a %= 2; cout << "a %= 2 的结果" << a << endl; return 0; }
a += 2 的结果4 a -= 2 的结果2 a *= 2 的结果4 a /= 2 的结果2 a %= 2 的结果0
三、比较运算符
用表达式比较,返回一个布尔值
#include <iostream> using namespace std; int main() { //比较运算 int a = 1; int b = 2; cout << (a == b) << endl; cout << (a != b) << endl; cout << (a < b) << endl; cout << (a > b) << endl; cout << (a <= b) << endl; cout << (a >= b) << endl; return 0; }
0 1 1 0 1 0
四、逻辑运算符
根据表达式的值,返回布尔值
#include <iostream> using namespace std; int main() { //逻辑运算符 bool flag1 = true; bool flag2 = false; cout << flag1 << endl; cout << flag2 << endl; cout << !flag2 << endl; cout << (flag2 && flag1) << endl; cout << (flag1 || flag2) << endl; int a = 19; int b = 0; cout << !b << endl; cout << (a || b) << endl; return 0; }
1 0 1 0 1 1 1