目录
1 算术运算符
2 赋值运算符
3 比较运算符
4 逻辑运算符
作用:用于执行代码的运算
运算符类型 | 作用 | 算术运算符 | 用于处理四则运算 | 赋值运算符 | 用于将表达式的值赋给变量 | 比较运算符 | 用于表达式的比较,并返回一个真值或假值 | 逻辑运算符 | 用于根据表达式的值返回真值或假值 |
1 算术运算符
作用:用于处理四则运算
加减乘除:
#include<iostream>
using namespace std;
int main() {
//加减乘除
int a1 = 56;
int b1 = 32;
cout << a1 + b1 << endl;
cout << a1 - b1 << endl;
cout << a1 * b1 << endl;
cout << a1 / b1 << endl;//两整数做相除的运算,结果仍为整数
int a2 = 10;
int b2 = 20;
cout << a2 / b2 << endl;
int a3 = 10;
int b3 = 0;
//cout << a3 / b3 << endl;//除数不能为0
//小数相除
double d1 = 0.26;
double d2 = 0.265;
cout << d1 / d2 << endl;//运算结果是double类型
system("pause");
return 0;
}
取模:
#include<iostream>
using namespace std;
int main() {
//取模,本质就是求余数
int a1 = 20;
int b1 = 6;
cout << a1 % b1 << endl;
int a2 = 10;
int b2 = 20;
cout << a2 % b2 << endl;
int a3 = 10;
int b3 = 0;
//cout << a3 % b3 << endl;//除数不能为0
//小数不能做取模运算
system("pause");
return 0;
}
递增递减:
#include<iostream>
using namespace std;
int main() {
//前置递增
int a = 10;
++a;//变量+1
cout << "a = " << a << endl;
//后置递增
int b = 10;
b++;//变量+1
cout << "b = " << b << endl;
//前置和后置的区别
//前置递增 先让变量+1 然后进行表达式运算
int a2 = 10;
int b2 = ++a2 * 10;
cout << "a2 = " << a2 << endl;
cout << "b2 = " << b2 << endl;
//后置递增 先进行表达式的运算,后让变量+1
int a3 = 10;
int b3 = a3++ * 10;
cout << "a3 = " << a3 << endl;
cout << "b3 = " << b3 << endl;
system("pause");
return 0;
}
2 赋值运算符
作用:用于将表达式的值赋给变量
运算符 | 术语 | 示例 | 结果 | = | 赋值 | a=2 | a=2 | += | 加等于 | a=0;a+=2; | a=2 | -= | 减等于 | a=5;a-=3 | a=2 | *= | 乘等于 | a=2;a*=2 | a=4 | /= | 除等于 | a=4;a/=2 | a=2 | %= | 模等于 | a=3;a%=2 | a=1 |
#include<iostream>
using namespace std;
/*
赋值运算符
*/
int main() {
//=
int a = 10;
a = 100;
cout << "a = " << a << endl;
//+=
int b = 10;
b += 2;
cout << "b = " << b << endl;
//-=
int c = 10;
c -= 2;
cout << "c = " << c << endl;
//*=
int d = 10;
d *= 2;
cout << "d = " << d << endl;
///=
int e = 10;
e /= 2;
cout << "e = " << e << endl;
//%=
int f = 10;
f %= 2;
cout << "f = " << f << endl;
system("pause");
return 0;
}
3 比较运算符
作用:用于表达式的比较,并返回一个真值或假值
运算符 | 术语 | 示例 | 结果 | == | 相等于 | 4==3 | 0 | != | 不等于 | 4!=3 | 1 | < | 小于 | 4<3 | 0 | > | 大于 | 4>3 | 1 | <= | 小于等于 | 4<=3 | 0 | >= | 大于等于 | 4>=3 | 1 |
#include<iostream>
using namespace std;
/*
比较运算符
*/
int main() {
//==
int a = 10;
int b = 20;
cout << (a == b) << endl;
//!=
cout << (a != b) << endl;
//<
cout << (a < b) << endl;
//>
cout << (a > b) << endl;
//<=
cout << (a <= b) << endl;
//>=
cout << (a >= b) << endl;
system("pause");
return 0;
}
4 逻辑运算符
作用:用于根据表达式的值返回真值或假值
运算符 | 术语 | 示例 | 结果 | ! | 非 | a=0;a=!a | a=1 | && | 与 | a=0;b=1;c=a&&b | c=0 | || | 或 | a=0;b=1;c=a||b | c=1 |
#include<iostream>
using namespace std;
/*
逻辑运算符
*/
int main() {
int a = 1;
int b = 0;
//! 非
cout << !a << endl;
cout << !!a << endl;
//&&与
cout << (a&&b) << endl;
//||或
cout << (a||b) << endl;
system("pause");
return 0;
}
|