定义临时变量
定义一个中间变量用来交换两个数。就如同要把两杯水交换,可以借助第三个杯子,进行交换。代码如下:
#include<stdio.h>
#include<stdlib.h>
//最简单的定义中间变量
int main()
{
int a = 7;
int b = 8;
int tem;
printf("交换前:a=7,b=8\n");
if (a != b)
{
tem = a;
a = b;
b = tem;
}
printf("交换后:a=%d,b=%d\n", a, b);
system("pause");
return 0;
}
//将其封装成函数
#include<stdio.h>
#include<stdlib.h>
void Swap(int *p1,int *p2)
{
int tmp = 0;
tmp = *p1;
*p1 = *p2;
*p2= tmp;
}
int main()
{
int a = 3;
int b = 6;
printf("%d %d\n", a, b);
Swap(&a, &b);//传址调用
printf("%d %d", a, b);
system("pause");
return 0;
}
无临时变量
采用两数先相加再相减的方式,该方法的问题在于可能存在两数相加会溢出的问题
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 10;
int b = 20;
printf("a=%d b=%d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;
}
异或的方式
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 9;//1001
int b = 5;//0101
printf("交换前:a=%d b=%d\n", a, b);
a = a^b; //a=1001^0101=1100
b = a^b;//b=1100^0101=1001=9
a = b^a;//a=1001^1100=0101=5
printf("交换后:a=%d b=%d\n", a, b);
system("pause");
return 0;
}