C# 2个数字之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/339961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:49:01  来源:igfitidea点击:

Difference between 2 numbers

c#algorithmmathnumbers

提问by Germstorm

I need the perfect algorithm or C# function to calculate the difference (distance) between 2 decimal numbers.

我需要完美的算法或 C# 函数来计算 2 个十进制数之间的差异(距离)。

For example the difference between:
100and 25is 75
100and -25is 125
-100and -115is 15
-500and 100is 600

例如,
10025之间的差异是75
100-25125
-100-11515
-500100600

Is there a C# function or a very elegant algorithm to calculate this or I have to go and handle every case separately with ifs.

是否有 C# 函数或非常优雅的算法来计算这个,或者我必须使用if分别处理每个案例。

If there is such a function or algorithm, which one is it?

如果有这样的函数或算法,它是哪个?

采纳答案by terjetyl

You can do it like this

你可以这样做

public decimal FindDifference(decimal nr1, decimal nr2)
{
  return Math.Abs(nr1 - nr2);
}

回答by Martin

result = Math.Abs(value1 - value2);

回答by johnc

I don't think it's possible in C#, you may need to look at implementing it in Assembler

我认为在 C# 中是不可能的,您可能需要考虑在 Assembler 中实现它

回答by Mecki

Just adding this, as nobody wrote it here:

只是添加这个,因为没有人在这里写过:

While you can surely use

虽然你肯定可以使用

Math.Abs(number1 - number2);

which is the easiest solution (and accepted answer), I wonder nobody wrote out what Abs actually does. Here's a solution that works in Java, C, C# and every other language with C like syntax:

这是最简单的解决方案(也是公认的答案),我想知道没有人写出 Abs 的实际作用。这是一个适用于Java、C、C# 和其他类似 C 语法的语言的解决方案:

int result = number1 - number2;
if (result < 0) {
    result *= -1;
}

It's that simple. You can also write it like this:

就这么简单。你也可以这样写:

int result = number1 > number2 ? number1 - number2 : number2 - number1;

The last one could be even faster once it got compiled; both have one if and one subtraction, but the first one has a multiplication in some cases, the last one has not. Why only in some cases? Some CPUs have a "swap sign" operation and the compiler recognizes what *= -1does, it just swaps the sign, so instead of a multiplication, it will issue a swap sign operation for CPUs that offer it and this operation is as fast as a CPU operation can get (usually one clock cycle).

一旦编译完成,最后一个可能会更快;两者都有一个 if 和一个减法,但在某些情况下第一个有乘法,最后一个没有。为什么只在某些情况下?一些 CPU 有一个“交换符号”操作,编译器识别什么*= -1,它只是交换符号,所以它会为提供它的 CPU 发出交换符号操作而不是乘法,并且这个操作与 CPU 操作一样快可以得到(通常是一个时钟周期)。

The first code example is actually doing what Abs is doing in most implementations to make use of "swap sign" where supported, the last one will be faster on CPUs that have no "swap sign" and were multiplications are more expensive than additions (on modern CPUs they are often equally fast).

第一个代码示例实际上是做 Abs 在大多数实现中所做的事情,以在支持的情况下使用“交换符号”,最后一个代码示例在没有“交换符号”并且乘法比加法更昂贵的 CPU 上会更快(在现代 CPU 它们通常同样快)。

回答by 3263927 contra

This is how i do it in enterprise projects:

这就是我在企业项目中的做法:

namespace Extensions
{
    public class Functions
    {
        public static T Difference<T>(object x1, object x2) where T : IConvertible
        {
            decimal d1 = decimal.Parse(x1.ToString());
            decimal d2 = decimal.Parse(x2.ToString());

            return (T)Convert.ChangeType(Math.Abs(d1-d2), typeof(T));
        }
    }
}

and testing:

和测试:

namespace MixedTests
{
    [TestClass]
    public class ExtensionsTests
    {
        [TestMethod]
        public void Difference_int_Test()
        {
            int res2 = Functions.Difference<int>(5, 7);
            int res3 = Functions.Difference<int>(-3, 0);
            int res6 = Functions.Difference<int>(-3, -9);
            int res8 = Functions.Difference<int>(3, -5);

            Assert.AreEqual(19, res2 + res3 + res6 + res8);
        }

        [TestMethod]
        public void Difference_float_Test()
        {
            float res2_1 = Functions.Difference<float>(5.1, 7.2);
            float res3_1 = Functions.Difference<float>(-3.1, 0);
            double res5_9 = Functions.Difference<double>(-3.1, -9);
            decimal res8_3 = Functions.Difference<decimal>(3.1, -5.2);

            Assert.AreEqual((float)2.1, res2_1);
            Assert.AreEqual((float)3.1, res3_1);
            Assert.AreEqual(5.9, res5_9);
            Assert.AreEqual((decimal)8.3, res8_3);

        }
    }
}