The difference between the two numbers

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

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

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

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

+46
math c # algorithm numbers
Dec 04 '08 at 9:06
source share
4 answers

You can do it like this:

public decimal FindDifference(decimal nr1, decimal nr2) { return Math.Abs(nr1 - nr2); } 
+89
Dec 04 '08 at 9:11
source share
— -
 result = Math.Abs(value1 - value2); 
+30
Dec 04 '08 at 9:12
source share

Just add this since no one wrote it here:

While you can use

 Math.Abs(number1 - number2); 

which is the easiest solution (and accepted answer), I am surprised that no one wrote what Abs actually does. Here's a solution that works in Java, C, C # and any other language with syntax like C:

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

It is so simple. You can also write it like this:

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

The latter can be even faster if it is compiled (both have the same subtraction, but in the former case there is a multiplication in some cases, and the latter is not). The first one actually does the work of Abs.

+17
Dec 08 '08 at 11:11
source share

I don't think this is possible in C #, you might have to take a look at its implementation in Assembler

+6
Dec 04 '08 at 9:18
source share



All Articles