不产生第三个临时变量的前提交换两组数据
作者:互联网
方法一:(简单加减法实现运算)
#include <stdio.h> int main() { int a, b; a = 5; b = 7; printf("a=%d b=%d\n",a, b); printf("交换后:\n"); a = a + b; b = a - b; a = a - b; printf("a=%d b=%d\n",a, b); }
注意:这个算法只能解决部分问题,可能会溢出;
方法二:(异或)
#include <stdio.h> int main() { int a, b; a = 5; b = 7; printf("a=%d b=%d\n",a, b); printf("交换后:\n"); a = a^b; b = a^b; a = a^b; printf("a=%d b=%d\n",a, b); }
标签:include,变量,int,两组,交换,第三个,异或,printf,main 来源: https://blog.51cto.com/u_15144773/2693252