# C语言——五种方法实现两个变量的值交换

### 三、代码实现

``````#include<stdio.h>

void change(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

void main()
{
int a = 10, b = 100;
//方法一：使用中间变量
int temp;
temp = a;	//temp=10,a=10,b=100
a = b;		//temp=10,a=100,b=100
b = temp;	//temp=10,a=100,b=10
printf("a = %d, b = %d\n", a, b);

//方法二：使用指针，封装函数
a = 10;
b = 100;
change(&a,&b);
printf("a = %d, b = %d\n", a, b);

//方法三：使用加减法
a = 10;
b = 100;
a = a + b;	//a=110,b=100
b = a - b;	//a=110,b=10
a = a - b;	//a=100,b=10
printf("a = %d, b = %d\n", a, b);

//方法四：使用乘除法
a = 10;
b = 100;
a = a * b;	//a=1000,b=100
b = a / b;	//a=1000,b=10
a = a / b;	//a=100,b=10
printf("a = %d, b = %d\n", a, b);

//方法五：使用异或运算
a = 10;		//二进制：00001010
b = 100;	//二进制：01100100
a = a ^ b;	//a=01101110(110),b=01100100(100)
b = a ^ b;	//a=01101110(110),b=00001010(10)
a = a ^ b;	//a=01100100(100),b=00001010(10)
printf("a = %d, b = %d", a, b);
getchar();
}``````

### 四、运行结果

原文作者：ywxk2016
原文地址: https://blog.csdn.net/ywxk2016/article/details/89290759
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。