个人知识回顾加强记忆
方法一: 定义临时变量作为中间值交换,此处省略代码
方法二:
#include<stdio.h>int main(){ int a = 1; int b = 2; printf("a=%d,b=%d\n",a,b); a = b - a; b = b - a; a = b + a; printf("a=%d,b=%d\n",a,b); return 0; }
方法三: 位运算实现两数交换
#include<stdio.h> int main(){
int a = 1; int b = 2; printf("a=%d,b=%d\n",a,b); a = a ^ b; //1^2 b = a ^ b; //1^2^2 = 1 a = a ^ b; // 1^1^2=2 printf("a=%d,b=%d\n",a,b); return 0;
}
|