- 使用临时变量
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main() {
int a = 5, b = 10;
printf("交换前:");
printf("a=%d,b=%d\n", a, b);
int temp = a;
a = b;
b = temp;
printf("交换后:");
printf("a=%d,b=%d\n", a, b);
return 0;
}
- 不使用临时变量
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main() {
int a = 5, b = 10;
printf("交换前:");
printf("a=%d,b=%d\n", a, b);
a = a - b;
b = b + a;
a = b - a;
printf("交换后:");
printf("a=%d,b=%d\n", a, b);
return 0;
}
代码解释:
a = a - b;//原a和b的差值
b = b + a;//原a
a = b - a;//原b
- 不使用临时变量
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main() {
int a = 5, b = 10;
printf("交换前:");
printf("a=%d,b=%d\n", a, b);
a = a^b;
b = a^b;
a = a^b;
printf("交换后:");
printf("a=%d,b=%d\n", a, b);
return 0;
}
代码解释:
a = a^b;//a与b的二进制数中,相同值置为 0,不同值置为1
b = a^b;//(a ^ b) ^ b==a
a = a^b;//(a ^ b) ^ ((a ^ b) ^ b)==b
C运行结果: