不借助第三个变量实现两个变量的交换

在程序设计的过程中,经常需要完成两个变量的暂时交换,常用的方法是:引用第三方的同类型的中间变量,通过3次赋值操作完成:

 1 #include <stdio.h>
2  
3 int main(int argc, char *argv[]){
4     int x = 10;
5     int y = 20;
6  
7     printf("Befor swap: x: %d, y: %d ", x, y);
8     int temp;
9     temp = x;
10     x = y;
11     y = temp;
12     printf("After swap: x: %d, y: %d ", x, y);
13  
14     return 0;
15 }

运行结果:

Befor swap: x: 10, y: 20
After swap: x: 20, y: 10

Press ENTER or type command to continue

这是最常见的交换变量的方法。


下面是一种不借助于中间变量的方式,实现两个变量的交换:

 1 #include <stdio.h>
2  
3 int main(int argc, char *argv[]){
4     int x = 10;
5     int y = 20;
6  
7     printf("Befor swap: x: %d, y: %d ", x, y);
8     x = x + y;
9     y = x - y;
10     x = x - y;
11     printf("After swap: x: %d, y: %d ", x, y);
12  
13     return 0;
14 }

Befor swap: x: 10, y: 20
After swap: x: 20, y: 10

Press ENTER or type command to continue

上边的这种方法需要对“=”符号的性质要非常清楚。

原文地址:https://www.cnblogs.com/guochaoxxl/p/6823186.html