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

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

问题描述

我希望能够交换两个变量,而在C#中使用临时变量。可以这样做?

 小数startAngle开始= Convert.ToDecimal(159.9);
小数stopAngle = Convert.ToDecimal(355.87);//交换每一:
// startAngle开始变为:355.87
// stopAngle变为:159.9


解决方案

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

不过对于答案的缘故,你可以使用这个code:

  startAngle开始=由startAngle + stopAngle;
stopAngle = startAngle开始,stopAngle;
由startAngle = startAngle开始,stopAngle;

问题都可以用四舍五入如果两个数字大不相同然而发生。这是由于浮点的性质

如果你想隐藏的临时变量,你可以使用一个实用方法:

 公共静态类Foo {    公共静态无效交换< T> (参考ŧLHS,裁判牛逼RHS){
        ŧTEMP = LHS;
        LHS = RHS;
        RHS =温度;
    }}

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

解决方案

First of all, swapping without a temp variable in a language as C# 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 points.

If you want to hide the temp 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天全站免登陆