算术运算符
- 加减乘除 (±*/)
注意除法(/):两个整数相除,结果仍是整数(取整);
除数不可以是0
#include<iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << a / b << endl; //输出是0
system("pause");
return 0;
}
两个小数可以相除,运算结果可以是小数
double d1 = 0.5;
double d2 = 0.22;
cout << d1 / d2 << endl;//输出是2.27273
- 取余(%)
本质是取余数;
两个数相除,除数不可以是0,也无法做取余运算;
两个小数之间不可以做取余运算(只有整型可以取余)
int a1 = 10;
int b1 = 3;
cout << a1 % b1 << endl;//输出是1
int a2 = 10;
int b2 = 20;
cout << a2 % b2 << endl;//输出是10
- 递增递减(++、- -)
前置递增递减
先让变量加减1,然后进行表达式运算
后置递增递减
先进行表达式运算,再让变量加减1
口诀:加在前,先加;加在后,后加
//前置
int a2 = 10;
int b2 = ++a2 * 10;
cout << "a2=" << a2 << endl; //a2=11
cout << "b2=" << b2 << endl; //b2=110
//后置
int a3 = 10;
int b3 = a3++ * 10;
cout << "a3=" << a3 << endl; //a3=11
cout << "b3=" << b3 << endl; //b3=100
赋值运算符
(±*/%)=
//+=
a = 10;
a += 2; //a=a+2;
cout << "a=" << a << endl; //a=12
//-=
a = 10;
a -= 2; //a=a-2
cout << "a=" << a << endl; //b=8
//%=
a = 10;
a %= 2; //a=a%2
cout << "a=" << a << endl; //a=0
比较运算符
- ==
- !=
- >
- <
- >=
- <=
返回的是 真假(0或1)
逻辑运算符
- 非( ! )—取反操作
- 与(&&)—a&&b (条件全为真,结果才是真)
- 或( || )—a||b (a或者b是真,就是真)
// !与
int a = 10;// 在C++中,非0都是真
cout << !a << endl;//输出是0
cout << !!a << endl;//输出是1
//&&和
// “同真为真,其余为假”
int b = 10;
cout << (a && b) << endl;//输出是1
int c = 0;
cout << (c && b) << endl;//输出是0
int d = 0;
cout << (c && d) << endl;//输出是0
// ||或
// “同假为假,其余为真”
int a = 10;
int b = 10;
cout << (a || b) << endl;//结果是1
int c = 0;
cout << (a || c) << endl;//结果是1
int d = 0;
cout << (c || d) << endl;//结果是0