C语言交换两个数的内容

C语言交换两个数的内容

1.创建临时变量交换两个数的内容
创建一个临时变量,把a的值先赋予c,再把b的值赋予a,最后把c的值给b,这样,a,b的内容就进行了交换。

#include <stdio.h>
int main() {

	int a = 10;
	int b = 20;
	int c = 0;
	c = a;
	a = b;
	b = c;
	printf("a=%d b=%d\n", a, b);
	system("pause");
	return 0;
}

2.不创建临时变量交换两个数的值
通过a,b之间简单的四则运算进行交换,根据两个数的不同,进行不同的四则运算

#include <stdio.h>
int main() {

	int a = 10;
	int b = 20;
	b = b - a;                                     //b=10
	a = a + b;                                    //a=10+10
	printf("a=%d b=%d\n", a, b);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a_hang_szz/article/details/88624809