当前位置:网站首页>给定两个整形变量的值,将两个值的内容进行交换 (C语言)
给定两个整形变量的值,将两个值的内容进行交换 (C语言)
2022-06-29 09:27:00 【西宏柿王多鱼】
第一种方法:
定义一个临时变量temp来进行a和b的值交换,代码如下:
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
int temp = 0;
printf("初始值: a=%d, b=%d\n",a,b);
temp = a;//temp=5
a = b;//a=15
b = temp;//b=5
printf("交换后: a=%d, b=%d\n",a,b);
return 0;
}

第二种方法:
不定义临时变量,通过利用a和b差值(也可以利用其他运算)进行交换,代码如下:
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
printf("初始值: a=%d, b=%d\n",a,b);
a = a-b;//a=-10
b = b+a;//b=5
a = b-a;//a=15
printf("交换后: a=%d, b=%d\n",a,b);
return 0;
}第三种方法:
不定义临时变量,通过异或(对两个数二进制各个比特位进行异或,相同为0,相异为1)的方法对a和b的值进行交换,代码如下:
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
printf("初始值: a=%d, b=%d\n",a,b);
a ^= b;
b ^= a;
a ^= b;
printf("交换后: a=%d, b=%d\n",a,b);
return 0;
}

边栏推荐
- To 3 --- 最后的编程挑战
- C # use winexec to call exe program
- Wandering --- 最后的编程挑战
- L2-3 is this a binary search tree- The explanation is wonderful
- 1021 Deepest Root (25 分)
- 2019-11-10 training summary
- 通过Win32API调用另一界面的按钮
- Basic operations during dev use
- Analysis on the specific execution process of an insert statement in MySQL 8.0 (2)
- 1146 Topological Order (25 分)
猜你喜欢
随机推荐
Oracle重置序列发生器(非重建)
View CSDN blog rankings
std::make_shared<T>/std::make_unique<T>与std::shared_ptr<T>/std::unique_ptr<T>的区别与联系
Power strings [KMP cycle section]
qgis制图
打印1000~2000年之间的闰年(C语言)
To 3 --- 最后的编程挑战
云主机端口扫描
Recurrence of vulnerability analysis for Cisco ASA, FTD and hyperflex HX
Web漏洞手动检测分析
Devaxpress double click to get cell data
Download control 1 of custom control (downloadview1)
C#中Linq常用用法
C语言库函数--strstr()
HDU 4578 transformation (segment tree + skillful lazy tag placement)
函数指针、函数指针数组、计算器+转移表等归纳总结
winform使用zxing生成二维码
Call another interface button through win32API
mysql 8.0 一条insert语句的具体执行流程分析(三)
Application of Pgp in encryption technology









