交换两个数字,不借助于第三个变量的三种简单的方法。
2012-03-23 16:18
330 查看
#include <stdio.h> int main() { int a = 10,b=20; // solution 1: a = a+b; b = a-b; a = a-b; printf("*********************************************\n"); printf("Change two number without another number!!!!\n"); printf("*********************************************\n"); printf("Solution 1:\n"); 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); printf("*********************************************\n"); printf("Solution 2:\n"); // solution 2: a = 10; b = 20; 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); printf("*********************************************\n"); printf("Solution 3:\n"); // solution 3:a^=b^=a^=b; a = 10; b = 20; printf("a:%d b:%d\n",a,b); a = a^b;//put the information into a b = a^b;//make b equal to the orginal a a = a^b;//make a equal to the orginal b printf("c:%d d:%d\n",a,b); return 0; }
以上为三种交换两个整数数字不借助于第三个变量的方法。。其中最好的为第一种方法,因为针对后两种方法。如果交换的不是整数,那么就会出现差错。
相关文章推荐
- 浅谈不使用第三个变量交换两个变量的值的方法
- 两个变量里的数字进行交换,不依赖第三个变量
- 不使用第三方变量交换两个变量值的三种方法
- [2016/12/5]不用第三个变量交换两个数字
- 交换两个变量的值,不使用第三个变量的四种方法
- 交换两个变量的值的方法-----从简单问题入手
- 交换两个变量的值,不使用第三个变量的四种方法
- Java--交换两个变量的值的三种方法:借助中间量交换,数值相加减交换,位移运算交换
- 交换两个变量的值-三种方法
- 不利用第三个变量交换两个数字的值
- C语言基础—实现两个变量交换的三种方法
- 交换两个变量的值,不使用第三个变量的四种方法
- 交换两个变量的值,不使用第三个变量的四种方法
- (转)三种方法解决两个变量数据的交换--Ctamor
- 三种方法实现不引入变量交换两个变量值
- 零基础学C语言 笔记三 三种方法交换两个变量的值
- 三种交换两个数字的方法
- 简单算法 - 交换两个整数的三种方法
- 交换两个变量的值,不使用第三个变量的方法
- 三种方法实现不引入变量交换两个变量值