int main()
{
int a = 3;
int b = 5;
printf("交换前:a=%d b=%d\n", a, b);
a = a ^ b;
b = a ^ b;//a^b^b=a
a = a ^ b;//a^b^a=b
printf("交换后:a=%d b=%d\n", a, b);
第一步:a = a ^ b; b保持不变
第二步:b = a ^ b;//这时b = a ^ b ^ b = a ^ 0 = a, 此时a的值赋值给了b
第三步:a = a ^ b;//这时a = a ^ b ^ a = b ^ 0 = b, 此时b的值赋值给了a
具体程序实现如下:
int main()
{
int a = 3;
int b = 5;
printf("交换前:a=%d b=%d\n", a, b);
a = a ^ b;
b = a ^ b;//a^b^b=a
a = a ^ b;//a^b^a=b
printf("交换后:a=%d b=%d\n", a, b);
登录后提交答案