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

1 Answer

0 votes
// Function that returns the distance between two decimal numbers
fn distance_between(a: f64, b: f64) -> f64 {
    // The distance is the absolute value of the difference
    (a - b).abs()
}

fn main() {
    // Test values
    let x1: f64 = 100.0;
    let y1: f64 = 45.0;

    let x2: f64 = 100.0;
    let y2: f64 = -15.0;

    let x3: f64 = -100.0;
    let y3: f64 = -125.0;

    let x4: f64 = -600.0;
    let y4: f64 = 100.0;

    // Print results
    println!("Distance between {} and {} = {}", x1, y1, distance_between(x1, y1));
    println!("Distance between {} and {} = {}", x2, y2, distance_between(x2, y2));
    println!("Distance between {} and {} = {}", x3, y3, distance_between(x3, y3));
    println!("Distance between {} and {} = {}", x4, y4, distance_between(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

...