How to find the median among three given numbers in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm> // for std::min and std::max

// Function to compute the median of three numbers
int median_of_three_numbers(int a, int b, int c) {
    return a + b + c - std::min({a, b, c}) - std::max({a, b, c});
}

int main() {
    // Test cases similar to your Python example
    std::cout << "The median of [1, 1, 1] is "
              << median_of_three_numbers(1, 1, 1) << std::endl;

    std::cout << "The median of [10, 3, 7] is "
              << median_of_three_numbers(10, 3, 7) << std::endl;

    std::cout << "The median of [10, -10, -10] is "
              << median_of_three_numbers(10, -10, -10) << std::endl;

    std::cout << "The median of [3, 3, 5] is "
              << median_of_three_numbers(3, 3, 5) << std::endl;
}


/*
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
0 votes
#include <iostream>

using std::cout;
using std::endl;

// Check whether x is the median of (x, y, z)
bool isMedian(int x, int y, int z) {
    // x is median if it lies between y and z
    // (either y <= x <= z OR z <= x <= y)
    if ((x >= y && x <= z) || (x <= y && x >= z)) {
        return true;
    } else {
        return false;
    }
}

// Return the median of three numbers using the helper function
int median_of_three_numbers(int a, int b, int c) {
    if (isMedian(a, b, c)) {
        return a;
    }
    if (isMedian(b, c, a)) {
        return b;
    }
    // If neither a nor b is the median, then c must be
    return c;
}

int main() {
    cout << "The median of [1, 1, 1] is "
         << median_of_three_numbers(1, 1, 1) << endl;

    cout << "The median of [10, 3, 7] is "
         << median_of_three_numbers(10, 3, 7) << endl;

    cout << "The median of [10, -10, -10] is "
         << median_of_three_numbers(10, -10, -10) << endl;

    cout << "The median of [3, 3, 5] is "
         << median_of_three_numbers(3, 3, 5) << endl;

    return 0;
}



/*
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
...