指派運算

指派的概念其實非常的簡單,最基本的指派運算子就是「=」。等號可以將右邊的值寫入左邊的變數中。

指派運算子

A += B;等同於A = A + B; 以下為其他的指派運算子:

運算子

意思

範例

=

指派

A = B

+=

相加並指派

A += B

-=

相減並指派

A -= B

*=

相乘並指派

A *= B

/=

相除並指派

A /= B

%=

取餘數並指派

A %= B

|=

或(OR)並指派

A |= B

&=

且(AND)並指派

A &= B

^=

XOR並指派

A ^= B

<<=

向左位移並指派

A <<= B

>>=

向右位移並指派

A >>= B

範例Code

#include <iostream>
using namespace std;

int main() {
    int a = 5;
    int b = 2;
    
    cout << "a = " << a << ", b = " << b << ", a += b : " << (a += b) << endl;
    cout << "a = " << a << ", b = " << b << ", a -= b : " << (a -= b) << endl;
    cout << "a = " << a << ", b = " << b << ", a *= b : " << (a *= b) << endl;
    cout << "a = " << a << ", b = " << b << ", a /= b : " << (a /= b) << endl;
    cout << "a = " << a << ", b = " << b << ", a |= b : " << (a |= b) << endl;
    cout << "a = " << a << ", b = " << b << ", a <<= b : " << (a <<= b) << endl;
    
    return 0;
}   

範例輸出:

a = 5, b = 2, a += b : 7

a = 7, b = 2, a -= b : 5

a = 5, b = 2, a *= b : 10

a = 10, b = 2, a /= b : 5

a = 5, b = 2, a |= b : 7

a = 7, b = 2, a <<= b : 28

Last updated