zoukankan      html  css  js  c++  java
  • 不借助第三个变量实现两个变量的交换

    在程序设计的过程中,经常需要完成两个变量的暂时交换,常用的方法是:引用第三方的同类型的中间变量,通过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

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

  • 相关阅读:
    1,Window安装Docker
    字符串编码
    hive自带derby数据库初始化
    numpy深浅复制
    matplotlib基础学习
    pandas基础学习
    numpy基础学习
    pandas之join、merge
    pandas之索引
    pandas之时间戳
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/6823186.html
Copyright © 2011-2022 走看看