1. 程式人生 > >異或交換兩個變數的值

異或交換兩個變數的值

通常做法

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int a=10, b=20,temp;
    temp=a;
    a=b;
    temp=b;
    printf("a=%d b=%d", a, b);
    system("pause");
    return 0;

}

關於異或

當兩兩數值異或值為0.而有一數值不同時為1..

                                          異或真值表:

 

A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

 

C語言中異或操作即是將兩個整數的二進位制每一位進行異或

例:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int a=10, b=20;     //0110   1010
    a = a^b;               //a=0110^1010=1100
    b = b^a;               //b=1010^1100=0110
    a = b^a;               //a=0110^1100=1010
    printf("%d %d", a, b);
    system("pause");
    return 0;
}