目录
1, 算数运算符
算数运算符有+, -, * , /, %, ++, --
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
//加法
cout << "a + b = " << a + b << endl;
//减法
cout << "a - b = " << a - b << endl;
//剩法
cout << "a * b = " << a * b << endl;
//除法
//整数相除, 舍去小数, 保留整数
//小数相除, 不舍去小数
cout << "a / b = " << a / b << endl;
//取余, 仅支持整型取余
cout << "a % b = " << a % b << endl;
//前置++,先对操作数自加1, 再进行表达式运算
//结果预期为31
cout << "++a + b = " << ++a + b << endl;
//后置++,先进行表达式运算, 再对操作数自加1
//结果预期为30
a = 10;
cout << "a++ + b = " << a++ + b << endl;
//前置--, 先对操作数自减1, 再进行表达式运算
//结果预期为29
a = 10;
cout << "--a + b = " << --a + b << endl;
//后置--,先进行表达式运算, 再对操作数自减1
//结果预期为30
a = 10;
cout << "a-- + b = " << a-- + b << endl;
system("pause");
return 0;
}
---------------------------------------------------------
输出:
a + b = 30
a - b = -10
a * b = 200
a / b = 0
a % b = 10
++a + b = 31
a++ + b = 30
--a + b = 29
a-- + b = 30
2, 复合运算符
复合运算符有 +=, -= , *=, /=, %=
#include <iostream>
using namespace std;
int main()
{
int a = 10;
//复合运算符+=
a += a;
cout << "a = " << a << endl;
//复合运算符-=
a -= a;
cout << "a = " << a << endl;
//复合运算符*=
a = 10;
a *= a;
cout << "a = " << a << endl;
//复合运算符/=
a = 10;
a /= a;
cout << "a = " << a << endl;
//复合运算符%=
a = 10;
a %= a;
cout << "a = " << a << endl;
system("pause");
return 0;
}
---------------------------------------------------------
输出:
a = 20
a = 0
a = 100
a = 1
a = 0
3, 比较运算符
比较运算符有>, >=,< ,<= , ==, !=, 返回bool值(数字1为真, 数字0为假),用于比较的表达式需要用括号括起来, 避免运算符优先级问题
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
//比较运算符>
cout << "a > b的结果:" << (a > b) << endl;
//比较运算符>=
cout << "a >= b的结果:" << (a >= b) << endl;
//比较运算符<
cout << "a < b的结果:" << (a < b) << endl;
//比较运算符<=
cout << "a <= b的结果:" << (a <= b) << endl;
//比较运算符==
cout << "a == b的结果:" << (a == b) << endl;
//比较运算符!=
cout << "a != b的结果:" << (a != b) << endl;
system("pause");
return 0;
}
---------------------------------------------------------
输出:
a > b的结果:0
a >= b的结果:0
a < b的结果:1
a <= b的结果:1
a == b的结果:0
a != b的结果:1
4, 逻辑运算符
逻辑运算符有&&(与), ||(或), !(非), 返回bool值(数字1为真, 数字0为假)
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
//逻辑非
cout << "!a的结果" << !a << endl;
//连续逻辑非
cout << "!!a的结果" << !!a << endl;
//逻辑与
cout << "a && b的结果:" << (a && b) << endl;
//逻辑或
cout << "a || b的结果:" << (a || b) << endl;
system("pause");
return 0;
}
---------------------------------------------------------
输出:
!a的结果0
!!a的结果1
a && b的结果:1
a || b的结果:1