运算符:用于执行代码的运算 1、算术运算符 整数相除,小数部分舍去,结果依然是整数;小数不可以做取余运算;
运算符 | 术语 | 示例 | 结果 |
---|
+ | 正号 | +3 | 3 | - | 负号 | -3 | -3 | + | 加 | 10+5 | 15 | - | 减 | 10-5 | 5 | *???????? | 乘 | 10*5 | 50 | / | 除 | 10/5 | 2 | % | 取模(取余) | 10%3 | 1 | ++ | 前置递增 | a=2;b=++a; | a=3;b=3; | ++ | 后置递增 | a=2;b=a++; | a=3;b=2; | -- | 前置递减 | a=2;b=--a; | a=1;b=1; | -- | 后置递减 | a=2;b=a--; | a=1;b=2; |
#include<iostream>
#include<string>
using namespace std;
int main()
{
//加减乘除
int a = 10;
int b = 3;
cout << a + b << endl;
cout << a - b << endl;
cout << a * b << endl;
cout << a / b << endl;//整数相除,小数部分舍去,结果依然是整数
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
//取模运算
int a = 10;
int b = 3;
cout << a % b << endl;
//两个小数不可以做取模运算
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
//1、前置递增
int a = 10;
++a;//让变量+1
cout << "a=" << a << endl;
//2、后置递增
int b = 10;
b++;//让变量+1
cout << "b=" << b << endl;
//3、前置和后置的区别
//前置递增 先让变量+1,然后进行表达式运算
int c = 10;
int d = ++c * 10;
cout << "c=" << c<< endl;
cout << "d=" << d << endl;
//后置递增 先进行表达式运算,然后让变量+1
int e = 10;
int f = e++ * 10;
cout << "e=" << e << endl;
cout << "f=" << f << endl;
system("pause");
return 0;
}
2、赋值运算符?
作用:将表达式的值赋给变量
运算符 | 术语 | 示例 | 结果 |
---|
= | 赋值 | a=2;b=3 | a=2;b=3; | += | 加等于 | 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>
#include<string>
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;
//%=
a = 10;
a %= 2; // a = a % 2
cout << "a=" << a << 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>
#include<string>
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 | 如果a为假,则a为真,如果a为真,则a为假 | && | 与 | a&&b | 如果a和b都为真,则结果为真,否则为假 | || | 或 | A||b | 如果a和b有一个为真,则结果为真,二者都为假时,结果为假 |
#include<iostream>
#include<string>
using namespace std;
int main()
{
//逻辑运算符
// !
int a = 10;
int b = 10;
//C++中,除了0都为真
cout << !a << endl;
cout << !!b << endl;
//&&
cout << (a&&b) << endl;
a = 0;
b = 10;
cout << (a && b) << endl;
//||
cout << (a || b) << endl;
a = 0;
b = 0;
cout << (a || b) << endl;
system("pause");
return 0;
}
|