如何交换而不第三变量? [英] How to swap without a third variable?
问题描述
我不得不换用数值两个变量,而无需使用第三个变量。什么是简单的解决方案?
I have to swap two variables with a number value without using a third variable. What is the simple solution?
推荐答案
让我们看到了方法之一就是通过使用算术运算符。
考虑2个变量例如x = 50和y = 70,让我们来看看如何交换两个变量的值,使x = 70和y = 50,而无需使用第三个变量。这可以通过使用以下的算术运算来完成,即
X = X + Y
$ B $由=说明X - Y
X =说明X - Y
上给出了
•X = X + Y给出了X = 70 + 50的这样x是等于120
•Y = X - ý给出Y = 120 - 70使y的值作为50
•X =说明X - Y给X = 120 - 50,因此x的值变为70
Let us see one of the method namely by using arithmetic operators.
Consider 2 variables say x=50 and y=70 and let us see how to swap the value of two variables that is make x=70 and y=50 without using third variable. This can be done by using following arithmetic operations namely
x= x + y
y= x - y
x= x - y
Which gives
• x= x + y gives x= 70 + 50 an so x is equal to 120
• y= x - y gives y = 120 - 70 which makes the value of y as 50
• x= x - y gives x= 120 - 50 and thus value of x becomes 70
这篇关于如何交换而不第三变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!