不使用临时变量交换两个变量 [英] Swap two variables without using a temporary variable

查看:26
本文介绍了不使用临时变量交换两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在 C# 中不使用临时变量的情况下交换两个变量.可以这样做吗?

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

推荐答案

首先,像 C# 一样在语言中没有临时变量的交换是一个非常糟糕的主意.

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;
    }
}

这篇关于不使用临时变量交换两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆