1.借助临时变量
</pre><pre name="code" class="objc">#include <stdio.h>
int main()
{
int a=0;
int b=0;
printf("please enter (a,b)");
scanf("%d%d",&a,&b);
printf("before:a=%d b=%d \n",a,b);
a=a+b;
b=a-b;//b=a+b-b=a
a=a-b;//a=a+b-a=b
printf("after:a=%d b=%d",a,b);
return 0;
}
2.加法实现
#include <stdio.h>
int main()
{
int a=0;
int b=0;
printf("please enter (a,b)");
scanf("%d%d",&a,&b);
printf("before:a=%d b=%d \n",a,b);
a=a+b;
b=a-b;//b=a+b-b=a
a=a-b;//a=a+b-a=b
printf("after:a=%d b=%d",a,b);
return 0;
}
3.异或实现
异或:两个值不相等时结果为真。如:1^1=0
1^0=1
0^0=0
0^1=1
则 1^0^1=0 得出一个结论:相同数异或会抵消。这也是实现两个数交换的依据。
#include <stdio.h>
int main()
{
int a=0;
int b=0;
printf("please enter (a,b)");
scanf("%d%d",&a,&b);
printf("before:a=%d b=%d \n",a,b);
a=a^b;
b=a^b;//b=a^(b^b)=a
a=a^b;//a=(a^a)^b=b
printf("after:a=%d b=%d",a,b);
return 0;
}