运算符+、-、*、/、%和=分别是加、减、乘、除、求余和赋值。
前面5个运算符,可以和赋值运算符“=”结合使用。
上代码:
#include<iostream> int main() { using namespace std; int a = 1, b = 5; //初始化a=1,b=5 cout << "a = " << a << "\nb = " << b << endl; a += b; //a+=b实际上是a=a+b cout << endl << "a += b" << endl; cout << "a = " << a << "\nb = " << b << endl; a -= b; //a-=b实际上是a=a-b cout << endl << "a -= b" << endl; cout << "a = " << a << "\nb = " << b << endl; a *= b; //a*=b实际上是a=a*b cout << endl << "a *= b" << endl; cout << "a = " << a << "\nb = " << b << endl; a /= b; //a/=b实际上是a=a/b,注意,由于是int,所以会取整数部分 cout << endl << "a /= b" << endl; cout << "a = " << a << "\nb = " << b << endl; a %= b; // a%=b实际上是a=a%b,即求a/b的余数 cout << endl << "a %= b" << endl; cout << "a = " << a << "\nb = " << b << endl; system("pause"); return 0; }
输出:
a = 1 b = 5 a += b a = 6 b = 5 a -= b a = 1 b = 5 a *= b a = 5 b = 5 a /= b a = 1 b = 5 a %= b a = 1 b = 5 请按任意键继续. . .
注意:
①组合运算符,对于等号右边的变量/常量并没有进行操纵,影响的是左边的变量。
②组合运算符,实际上就是 左边的数字+-*/右边的数字 后,赋值给左边的数字。
即a*=b 等价于a=a*b;