方法1:
#define swap(x,y) do{x=x+y;y=x-y;x=x-y;}while(0)
方法2:
#define swap(x,y) do{a^=b;b^=a;a^=b;}while(0)
说明:
-
a^=b;
:把a^b
结果赋值给a
-
b^=a;
:相当于b=b^(a^b)
。而b^(a^b)
等于a^b^b
。b^b
的结果为0
,因为同一个数与本身相异或,结果必为0
。因此b
的值等于a^0
,即a
-
a^=b;
:由于a
的值等于a^b
,b
的值等于a
,因此,相当于a=(a^b)^a
,即a
的值等于b^a^a
,相当于b^0
,等于b
注:此方法只适用于整型数据
方法3:
#define swap(x,y) do{typeof(x) t;t=x;x=y;y=t;}while(0)
#include <stdio.h>
#define swap1(x,y) do{x=x+y;y=x-y;x=x-y;}while(0)
#define swap2(x,y) do{a^=b;b^=a;a^=b;}while(0)
#define swap3(x,y) do{typeof(x) t;t=x;x=y;y=t;}while(0)
int main()
{
int a=2,b=3;
float fa=2.5f,fb=4.2f;
printf("交换前a=%d\t,b=%d\n",a,b);
swap1(a,b);
printf("交换后a=%d\t,b=%d\n\n",a,b);
printf("交换前a=%d\t,b=%d\n",a,b);
swap2(a,b);
printf("交换后a=%d\t,b=%d\n\n",a,b);
printf("交换前a=%d\t,b=%d\n",a,b);
swap3(a,b);
printf("交换后a=%d\t,b=%d\n\n",a,b);
printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
swap1(fa,fb);
printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);
printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
swap2(fa,fb);
printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);
printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
swap3(fa,fb);
printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);
return 0;
}
输出:
交换前a=2 ,b=3
交换后a=3 ,b=2
交换前a=3 ,b=2
交换后a=2 ,b=3
交换前a=2 ,b=3
交换后a=3 ,b=2
交换前fa=2.50 ,fb=4.20
交换后fa=4.20 ,fb=2.50
交换前fa=4.20 ,fb=2.50
交换后fa=4.20 ,fb=2.50
交换前fa=4.20 ,fb=2.50
交换后fa=2.50 ,fb=4.20
网友评论