关于两个变量交换的几种方法。

一、借助第三个变量

#include 
#include 
int main()
{
	int a = 2, b = 8, temp = 0;
	temp = a;
	a =  b;
	b = temp;

	printf("a=%d  b=%d\n", a, b);


	system("pause");
	return 0;

}


二,运用函数

#include 
#include 
void swap(int *pa, int *pb){
	int tem = 0;
	tem = *pa;
	*pa = *pb;
	*pb = tem;
}
int main(){
	int a = 2;
	int b = 8;
	swap(&a, &b);
	printf("a=%d  b=%d\n",a, b);
	system("pause");
	return 0;
}

三、不借助第三个变量、

1、

#include 
#include 
int main()
{
	int a = 2, b = 8;
	a = a + b;
	b = a - b;
	a = a - b;

	printf("a=%d  b=%d\n", a, b);


	system("pause");
	return 0;

}

2、

#include 
#include 
int main()
{
	int a = 2;
	int b = 8;
	a = a^b;
	b = a^b;
	a = a^b;
	printf("a=%d  b=%d\n", a, b);
	system("pause");
	return 0;
}


你可能感兴趣的:(C语言)