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

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// Function that returns the distance between two decimal numbers
func distanceBetween(a float64, b float64) float64 {
    // The distance is the absolute value of the difference
    return math.Abs(a - b)
}

func main() {

    // Test values
    var x1 float64 = 100.0
    var y1 float64 = 45.0

    var x2 float64 = 100.0
    var y2 float64 = -15.0

    var x3 float64 = -100.0
    var y3 float64 = -125.0

    var x4 float64 = -600.0
    var y4 float64 = 100.0

    // Print results
    fmt.Println("Distance between", x1, "and", y1, "=", distanceBetween(x1, y1))
    fmt.Println("Distance between", x2, "and", y2, "=", distanceBetween(x2, y2))
    fmt.Println("Distance between", x3, "and", y3, "=", distanceBetween(x3, y3))
    fmt.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

...