1、算术运算符
算数运算符包括以下几种符号:
示例:
//作用:用于处理四则运算
#include<iostream>
using namespace std;
int main(){
int a1 = 10;
int b1 = 3;
//加减乘除运算
cout << "a1 + b1 = " << a1 + b1 << endl;
cout << "a1 - b1 = " << a1 - b1 << endl;
cout << "a1 * b1 = " << a1 * b1 << endl;
cout << "a1 / b1 = " << a1 / b1 << endl;//两个整数相除,结果仍是整数
double d1 = 0.5;
double d2 = 0.25;
cout << "d1 / d2 = " << d1 / d2 << endl;
//取模,小数不可以取模
int a2 = 10;
int b2 = 3;
cout << "a2 % b2 = " << a2 % b2 << endl;
//递增
//后置递增
int a = 10;
a++;
cout << "a++ = " << a << endl;//11
//前置递增
int b = 10;
++b;
cout << "++b = " << b << endl;//11
//区别
//前置递增先对变量进行++,再计算表达式
//后置递增先计算表达式,再对变量进行++
int a3 = 10;
int b3 = ++a3 * 10;
cout << "b3 = " << b3 << endl;
int a4 = 10;
int b4 = a4++ * 10;
cout << "b4 = " << b4 << endl;
cout << "a4 = " << a4 << endl;
system("pause");
return 0;
}
输出:
2、赋值运算符
赋值运算符包括以下几种符号:
示例:
//作用:将表达式赋值给变量
#include<iostream>
using namespace std;
int main(){
//赋值运算符
// =
int a = 10;
a = 100;
cout << "a = " << a << endl;
// +=
a = 10;
a += 2;// a = a + 2
cout << "a = " << a << endl;
// *=
a = 10;
a *=2;// a = a * 2
cout << "a = " << a << endl;
// /=
a = 10;
a /=2;// a = a / 2
cout << "a = " << a << endl;
// %=
a = 10;
a %=2;// a = a % 2
cout << "a = " << a << endl;
system("pause");
return 0;
}
输出:
3、比较运算符
比较运算符有以下几种符号:
示例:
//作用:用于表达式的比较,并返回一个真值或假值
#include<iostream>
using namespace std;
int main(){
int a = 10;
int b = 20;
cout << "(a == b)" << (a == b) << endl;//0
cout << "(a != b)" << (a != b) << endl;//1
cout << "(a > b)" << (a > b) << endl;//0
cout << "(a < b)" << (a < b) << endl;//1
cout << "(a >= b)" << (a >= b) << endl;//0
cout << "(a <= b)" << (a <= b) << endl;//1
system("pause");
return 0;
}
输出:
4、逻辑运算符
逻辑运算符有以下符号:
示例:
//用于根据表达式的值返回真值或假值
#include<iostream>
using namespace std;
int main(){
//逻辑运算符 --非,真变假,假变真
int a = 10;
cout << "!a = " << !a << endl;//0
cout << "!!a = " << !!a << endl;//1
//逻辑运算符 --与,同真为真,其余为假
a = 10;
int b = 10;
cout << "(a && b) = " << (a && b) << endl;//1
a = 10;
b = 5;
cout << "(a && b) = " << (a && b) << endl;//0
a = 0;
b = 0;
cout << "(a && b) = " << (a && b) << endl;//0
//逻辑运算符 --或,同假为假,其余为真
a = 10;
b = 10;
cout << "(a || b) = " << (a || b) << endl;//1
a = 10;
b = 0;
cout << "(a || b) = " << (a || b) << endl;//1
a = 0;
b = 0;
cout << "(a || b) = " << (a || b) << endl;//0
system("pause");
return 0;
}
输出: