方法一、此方法当a和b的数非常大时,可能会出现溢出的问题
#include <stdio.h>
int main()
{
int a = 2;
int b = 3;
printf("交换前 a=%d, b=%d\n", a, b);
a = a + b; //a为两数之和,b此时不变还是3
b = a - b; //此时b的值为5-3=2
a = a - b; //此时a的值为5-2=3
printf("交换后 a=%d, b=%d\n", a, b);
return 0;
}
方法二、可解决方法一缺点
#include <stdio.h>
int main()
{
int a = 2;
int b = 3;
printf("交换前a=%d,b=%d\n",a,b);
a = a ^ b; //010^011→001
b = a ^ b; //001^011→010
a = a ^ b; //001^010→011
printf("交换后a=%d,b=%d\n",a,b);
return 0;
}