
通过加法和减法操作,我们可以将两个数字从一个内存位置交换到另一个内存位置。
以下是算法的解释 −
Step 1: Declare 2 variables x and y. Step 2: Read two numbers from keyboard. Step 3: Swap numbers. //Apply addition and subtraction operations to swap the numbers. i. x=x+y ii. y=x-y iii. x=x-y Step 4: Print x and y values.
以下是一个C程序,用于解释如何在不使用第三个变量或临时变量的情况下交换两个数字:
#include<stdio.h>
int main(){
int x,y;
printf("enter x and y values:");
scanf("%d%d",&x,&y);// lets take x as 20 and y as 30
x=x+y;// x=20+30=50
y=x-y;//y=50-30=20
x=x-y;//x=50-20=30
printf("After swap x=%d and y=%d",x,y);
return 0;
}你将得到以下输出 −
enter x and y values:20 30 After swap x=30 and y=20
注意 - 我们可以使用乘法、除法和按位异或运算符来交换两个数字,而不需要使用第三个变量。
考虑另一个例子,它解释了如何使用乘法和除法运算符来交换两个数字。
以下是C程序,演示了交换两个数字的相应功能:
#include<stdio.h>
int main(){
int x,y;
printf("enter x and y values:");
scanf("%d%d",&x,&y);
x=x*y;
y=x/y;
x=x/y;
printf("After swap x=%d and y=%d",x,y);
return 0;
}当你执行上面的程序时,你将得到以下输出 −
enter x and y values:120 250 After swap x=250 and y=120
以上就是如何在C编程中不使用第三个或临时变量交换两个数字?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号