1.创建临时变量
#include <stdio.h>
int main()
{
int a = 9;
int b = 19;
printf("a=%d,b=%d\n", a, b);
int tmp = a;//创建临时变量储存a的值
a = b;
b = tmp;
printf("a=%d,b=%d\n", a, b);
return 0;
}
运行结果:
2.运用变量自身巧妙地交换两者
#include <stdio.h>
int main()
{
int a = 10;
int b = 9;
printf("a=%d,b=%d\n", a, b);
a = a + b;
b = a - b;//此时的a是a+b,相当于a+b-b
a = a - b;//a-b相当于a+b-a
printf("a=%d,b=%d", a, b);
}
结果:
3.按位异或运算
#include <stdio.h>
int main()
{
int a = 15;
int b = 30;
printf("a=%d,b=%d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a=%d,b=%d\n", a, b);
return 0;
}
运行结果: