Difference between 2 numbers

霸气de小男生 提交于 2019-11-28 09:34:49

You can do it like this

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

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:

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 *= -1 does, 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).

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).

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!