next up previous contents
Next: 實機練習題 Up: 運算子 Previous: Bitwise 運算子   Contents

設定運算子

  1. 設定運算子 (Assignment Operators) 說明:
    運算子 描述 例子
    = 將右邊的值設定給左邊的變數 C=A+B
    += 將右邊的值加到左邊的變數 C+=A, C=C+A
    -= 將左邊的變數減去右邊的值 C-=A, C=C-A
    *= 將左邊的變數乘以右邊的值 C*=A, C=C*A
    /= 將左邊的變數除以右邊的值 C/=A, C=C/A
    %= 左邊的變數為左邊變數除右邊變數取餘數 C%=A, C=C%A
    <<= 左邊變數 left shift 右邊值 C<<2, C=C<<2
    >>= 左邊變數 right shift 右邊值 C>>2, C=C>>2
    &= 左邊變數 bitwise AND 右邊值 C&=2, C=C&2
    ^= 左邊變數 bitwise exclusive OR 右邊值 C^=2, C=C^2
    |= 左邊變數 bitwise OR 右邊值 C|=2, C=C|2
  2. 範例程式
    [dywang@dyw219 zzz]$ vim op-as1.c 
    [dywang@dyw219 zzz]$ cat op-as1.c 
    #include <stdio.h>
    
    main() {
        int a, c;
    
        printf("Enter an integer: ");
        scanf("%d", &a);
    
        c = a;
        printf("c = a, c = %d\n", c );
    
        c += a;
        printf("c += a, c = %d\n", c );
    
        c -= a;
        printf("c -= a, c = %d\n", c );
        
        c *= a;
        printf("c *= a, c = %d\n", c );
        
        c /= a;
        printf("c /= a, c = %d\n", c );
        
        c = 200;
        c %= a;
        printf("c = 200\nc %= a, c = %d\n", c );
    
        a <<= 2;
        printf("a <<= 2, a = %d\n", a );
        
        a >>= 2;
        printf("a >>= 2, a = %d\n", a );
        
        a &= 2;
        printf("a &= 2, a = %d\n", a );
        
        a ^= 2;
        printf("a ^= 2, a = %d\n", a );
    
        a |= 2;
        printf("a |= 2, a = %d\n", a );
    }
    
  3. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o op-as1 op-as1.c
    
  4. 執行結果
    [dywang@dyw219 zzz]$ ./op-as1 
    Enter an integer: 21
    c = a, c = 21
    c += a, c = 42
    c -= a, c = 21
    c *= a, c = 441
    c /= a, c = 21
    c = 200
    c %= a, c = 11
    a <<= 2, a = 84
    a >>= 2, a = 21
    a &= 2, a = 0
    a ^= 2, a = 2
    a |= 2, a = 2
    



De-Yu Wang 2019-09-19