C语言实现:使用函数实现两个数的交换。

方法一:定义一个临时变量来作为介质来实现两个数的交换

#include
#include
#pragma warning(disable:4996)
void exchange(int* x, int* y)
{
	int z = 0;
	z = *y;
	*y = *x;
	*x = z;
}
int main()
{
	int x = 0;
	int	y = 0;//int x,y;
	scanf("%d %d", &x, &y);
	exchange(&x, &y);
	printf("交换后的x,y: %d %d\n", x, y);
	system("pause");
	return 0;
}

方法二:用按位与来实现两个数的交换
代码如下:

#include
#include
#pragma warning(disable:4996)
void exchange(int *x , int *y)
{
	*x = *x^*y;
	*y = *x^*y;
	*x = *x^*y;
}
int main()
{
	int x = 0;
	int	y = 0;//int x,y;
	scanf("%d %d", &x, &y);
	exchange(&x, &y);
	printf("交换后的x,y: %d %d\n", x, y);
	system("pause");
	return 0;
}

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