使用临时变量交换两个数的值
#include <stdio.h>
int main(){
//使用临时变量;
int a,b,c;
printf("请输入两个数:");
scanf("%d %d",&a,&b);
printf("使用临时变量交换前:%d %d\n",a,b);
c = b;
b = a;
a = c;
printf("使用临时变量交换后:%d %d\n",a,b);
return 0;
}
不使用临时变量交换两个数的值
#include <stdio.h>
int main(){
int a,b;
printf("请输入两个数:");
scanf("%d %d",&a,&b);
printf("不使用临时变量交换前:%d %d\n",a,b);
// 加入a=3(3的二进制:011),b=5(5的二进制:101);
a = a^b; // 110 = 011 ^ 101
b = a^b; // 011 = 110 ^ 101
a = a^b; // 101 = 110 ^ 011
printf("不使用临时变量交换后:%d %d\n",a,b);
return 0;
}