交换两个变量的值(4种方法)
来源:互联网 发布:购买自己的淘宝客链接 编辑:程序博客网 时间:2024/09/21 08:58
第一种,最简单最常用的。
#include<stdio.h>int main(){ int a=1,b=2; int c; c=a; a=b; b=c; printf("%d,%d\n",a,b); return 0;}
第二种,使用位运算。
#include<stdio.h>int main(){ int a=1,b=2; a=a^b; b=b^a; a=a^b; return 0;<pre name="code" class="cpp"> printf("%d,%d\n",a,b);}注: 0^X=X
a=X^Y
b=X^Y^Y=X
a=X^Y^X=Y
第三种,使用指针,调用函数。
#include<stdio.h>void exchange(int *a,int *b){ int c; c=*a; *a=*b; *b=c;}int main( ){ int a=1,b=2; int *p1,*p2; p1=&a; p2=&b; exchange(p1,p2); printf("%d,%d\n",a,b); return 0; }第四种,该方法是转载的,原文地址:点击打开链接
#include<stdio.h>int main (){//int a,b;int a=1,b=2; //printf("please enter two numbers.\n",);//scanf("%d,%d",&a,&b);a=b-a;b=b-a;a=b+a;printf("%d,%d\n",a,b);return 0;}
还有什么方法,欢迎大家补充!谢谢
0 0
- 交换两个变量的值(4种方法)
- 交换两个变量的值的方法
- 两个变量的值的交换方法
- 两个变量交换值的方法
- 交换两个变量的三种方法
- 两个变量交换的三种方法
- 两个变量交换的几种方法
- 交换两个变量的值,不借助第三个变量的四种方法(学习)
- Java交换两个变量的值的三种方法
- 交换两个变量的值的两种方法
- 四种交换两个变量的值的方法
- 两个变量交换值的三种方法
- 交换两个变量的值(三种方法)
- 交换两个变量的值(多种方法)
- 交换两个变量的(六种)方法分析
- 交换两个变量中的值(三种方法)
- 不用中间变量,交换两个变量的值的方法
- 两个变量不用中间变量交换值的方法
- 四、单片机软件模拟SPI接口—加深理解SPI总线协议
- 【DP】sgu104
- struts2文件上传
- 用信号量解决进程的同步与互斥探讨
- Swap Nodes in Pairs
- 交换两个变量的值(4种方法)
- 还是A+B
- lr_save_var函数
- MAC下安装MYSQL,压缩包形式安装
- NGUI与粒子遮挡解决方法
- Android 插件化
- 地理围栏算法解析
- JAVA基础笔记六——多线程
- REST client 基于浏览器的测试工具