How to calculates the distance between two decimal numbers (absolute difference) in C#

1 Answer

0 votes
using System;

class DistanceBetweenNumbers
{
    // Function that returns the distance between two decimal numbers
    static double DistanceBetween(double a, double b)
    {
        // The distance is the absolute value of the difference
        return Math.Abs(a - b);
    }

    static void Main()
    {
        // Test values
        double x1 = 100.0,  y1 = 45.0;
        double x2 = 100.0,  y2 = -15.0;
        double x3 = -100.0, y3 = -125.0;
        double x4 = -600.0, y4 = 100.0;

        // Print results
        Console.WriteLine("Distance between " + x1 + " and " + y1 + " = " + DistanceBetween(x1, y1));
        Console.WriteLine("Distance between " + x2 + " and " + y2 + " = " + DistanceBetween(x2, y2));
        Console.WriteLine("Distance between " + x3 + " and " + y3 + " = " + DistanceBetween(x3, y3));
        Console.WriteLine("Distance between " + x4 + " and " + y4 + " = " + DistanceBetween(x4, y4));
    }
}


/*
run:

Distance between 100 and 45 = 55
Distance between 100 and -15 = 115
Distance between -100 and -125 = 25
Distance between -600 and 100 = 700

*/

 



answered Jun 28 by avibootz

Related questions

...