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

1 Answer

0 votes
public class DistanceBetweenNumbers {

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

    public static void main(String[] args) {

        // Test values
        double x1 = 100,  y1 = 45;
        double x2 = 100,  y2 = -15;
        double x3 = -100, y3 = -125;
        double x4 = -600, y4 = 100;

        // Print results
        System.out.println("Distance between " + x1 + " and " + y1 + " = " + distanceBetween(x1, y1));
        System.out.println("Distance between " + x2 + " and " + y2 + " = " + distanceBetween(x2, y2));
        System.out.println("Distance between " + x3 + " and " + y3 + " = " + distanceBetween(x3, y3));
        System.out.println("Distance between " + x4 + " and " + y4 + " = " + distanceBetween(x4, y4));
    }
}


/*
run:

Distance between 100.0 and 45.0 = 55.0
Distance between 100.0 and -15.0 = 115.0
Distance between -100.0 and -125.0 = 25.0
Distance between -600.0 and 100.0 = 700.0

*/

 



answered Jun 28 by avibootz

Related questions

...