How to find the median among three given numbers in Rust

1 Answer

0 votes
/*
    Computes the median of three integers.
    The median is the value that is neither the minimum nor the maximum.

    Formula:
      median = a + b + c - min(a, b, c) - max(a, b, c)
*/
fn median_of_three_numbers(a: i32, b: i32, c: i32) -> i32 {
    // Determine the minimum of the three numbers
    let mut min = a;
    if b < min { min = b; }
    if c < min { min = c; }

    // Determine the maximum of the three numbers
    let mut max = a;
    if b > max { max = b; }
    if c > max { max = c; }

    // The median is the remaining value
    a + b + c - min - max
}

fn main() {
    // Test cases
    println!("The median of [1, 1, 1] is {}", median_of_three_numbers(1, 1, 1));
    println!("The median of [10, 3, 7] is {}", median_of_three_numbers(10, 3, 7));
    println!("The median of [10, -10, -10] is {}", median_of_three_numbers(10, -10, -10));
    println!("The median of [3, 3, 5] is {}", median_of_three_numbers(3, 3, 5));
}


/*
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10, -10, -10] is -10
The median of [3, 3, 5] is 3

*/

 



answered Mar 26 by avibootz
...