Swap two variables without using a temporary varia

2019-01-02 18:15发布

I'd like to be able to swap two variables without the use of a temporary variable in C#. Can this be done?

decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);

// Swap each:
//   startAngle becomes: 355.87
//   stopAngle becomes: 159.9

28条回答
低头抚发
2楼-- · 2019-01-02 18:22

You can try the following code. It is much more better than the other code.

a = a + b;
b = a - b;
a = a - b;
查看更多
妖精总统
3楼-- · 2019-01-02 18:23

The simple way to swap 2 numbers in just one line:

a=(a+b)-(b=a);

eg: a=1, b=2

Step 1: a=(1+2) - (b=1)

Step 2: a=3-1

=> a=2 and b=1


Efficient way is to use:

C Programming: (x ^= y), (y ^= x), (x ^= y);

Java: x = x ^ y ^ (y = x);

Python: x, y = y, x

Note: Most common mistake people make: //Swap using bitwise XOR (Wrong Solution in C/C++)

x ^= y ^= x ^= y; 

Source: GeeksforGeek

查看更多
美炸的是我
4楼-- · 2019-01-02 18:23
a = a + b
b = a - b
a = a - b

َ

查看更多
孤独总比滥情好
5楼-- · 2019-01-02 18:25

First of all, swapping without a temporary variable in a language as C# is a very bad idea.

But for the sake of answer, you can use this code:

startAngle = startAngle + stopAngle;
stopAngle = startAngle - stopAngle;
startAngle = startAngle - stopAngle;

Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.

If you want to hide the temporary variable, you can use a utility method:

public static class Foo {

    public static void Swap<T> (ref T lhs, ref T rhs) {
        T temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}
查看更多
琉璃瓶的回忆
6楼-- · 2019-01-02 18:25

With C# 7, you can use tuple deconstruction to achieve the desired swap in one line, and it's clear what's going on.

decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);

(startAngle, stopAngle) = (stopAngle, startAngle);
查看更多
君临天下
7楼-- · 2019-01-02 18:25
startAngle = (startAngle + stopAngle) - (stopAngle = startAngle);
查看更多
登录 后发表回答