不允许创建临时变量,交换两个数的内容。
第一种方法
1、思路:利用加减法。先求得两个数的和,在用和分别减去各自的数即可。
2、程序:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 1, b = 9;
a = a + b;
b = a - b;
a = a - b;
printf("输出a=%d,b=%d\n", a, b);
system("pause");
return 0;
}
第二种方法
1、思路:利用异或运算。异或运算是相同为0,不同为1.
2、程序:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 1, b = 9;
a = a^b;
b = a^b;
a = a^b;
printf("输出a=%d,b=%d\n", a, b);
system("pause");
return 0;
}