1.创建临时变量(最好使用这种方法)
int main()
{
int a=10;
int b=20;
int tmp=0;
printf("before:a:%d,b:%d\n",a,b);
tmp=a;
a=b;
b=tmp;
printf("after :a:%d,b:%d\n",a,b);
return 0;
}
2.加减法(可能会产生溢出)
int main()
{
int a=10;
int b=20;
printf("before:a:%d,b:%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("after :a:%d,b:%d\n",a,b);
return 0;
}
3.异或法(不会溢出,但是效率不如创建临时变量)
int main()
{
int a=10;
int b=20;
printf("before:a:%d,b:%d\n",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("after :a:%d,b:%d\n",a,b);
return 0;
}
标签:tmp,20,int,个数,元素,交换,printf,main,before
From: https://blog.51cto.com/u_16190077/7141343