当前位置:网站首页>Given the values of two integer variables, the contents of the two values are exchanged (C language)
Given the values of two integer variables, the contents of the two values are exchanged (C language)
2022-06-29 10:36:00 【Xihong Shiwang has many fish】
The first method :
Define a temporary variable temp To carry out a and b Value exchange of , The code is as follows :
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
int temp = 0;
printf(" Initial value : a=%d, b=%d\n",a,b);
temp = a;//temp=5
a = b;//a=15
b = temp;//b=5
printf(" After exchanging : a=%d, b=%d\n",a,b);
return 0;
}

The second method :
Do not define temporary variables , By using a and b Difference value ( Other operations can also be used ) swapping , The code is as follows :
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
printf(" Initial value : a=%d, b=%d\n",a,b);
a = a-b;//a=-10
b = b+a;//b=5
a = b-a;//a=15
printf(" After exchanging : a=%d, b=%d\n",a,b);
return 0;
}The third method :
Do not define temporary variables , By XOR ( XOR two binary bits , Same as 0, Dissimilarity is 1) The method of a and b The value of , The code is as follows :
#include <stdio.h>
int main ()
{
int a = 5;
int b = 15;
printf(" Initial value : a=%d, b=%d\n",a,b);
a ^= b;
b ^= a;
a ^= b;
printf(" After exchanging : a=%d, b=%d\n",a,b);
return 0;
}

边栏推荐
- C#MDI打开子窗体去掉自动生成的菜单栏
- 打印1000~2000年之间的闰年(C语言)
- Web漏洞手动检测分析
- AGCTFb部分题解
- Slide the custom control to close the activity control
- C#使用WinExec调用exe程序
- 二叉树
- PGP在加密技术中的应用
- I would like to know how to open an account for free online stock registration? In addition, is it safe to open a mobile account?
- October 17, 2020: question brushing 1
猜你喜欢

Automatic 3D Detection and Segmentation of Head and Neck Cancer from MRI Data.

Installing and configuring wmware esxi 6.5.0 in VMware Workstation

云主机端口扫描

Solve the problem that zxing's QR code contains Chinese garbled code

Arc view and arc viewpager

Reading notes of CLR via C -clr boarding and AppDomain

SQL Server 数据库的统计查询

BUUCTF--新年快乐

Fully understand the volatile keyword

Seaweedfs security configuration
随机推荐
SQL Server 数据库增删改查语句
Attribute in C
Summary after the 2009 ICPC Shanghai regional competition
2020-09-18 referer authentication URL escape
Comprehensive understanding of synchronized
Learn spark computing framework in practice (00)
Installing and configuring wmware esxi 6.5.0 in VMware Workstation
Learn spark computing framework in practice (01)
October 17, 2020: question brushing 1
2020-10-17:刷题1
L2-026 small generation (25 points)
Downloading and installing VMware (basic idea + detailed process)
C#中Linq常用用法
如何快速完成磁盘分区
Contents of advanced mathematics
Comment terminer rapidement une partition de disque
CLR via C reading notes - single instance application
Real time value transfer from C form to another form
查看CSDN的博客排名
2019.11.3 learning summary