异或交换两个变量的值

通常做法

#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;
}

猜你喜欢

转载自blog.csdn.net/w838325636/article/details/85250418