How to find the median among three given numbers in VB.NET

1 Answer

0 votes
Imports System

Module MedianOfThree

    '
    ' 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)
    '
    Function MedianOfThreeNumbers(a As Integer, b As Integer, c As Integer) As Integer
        Dim minVal As Integer = a
        Dim maxVal As Integer = a

        ' Determine the minimum of the three numbers
        If b < minVal Then minVal = b
        If c < minVal Then minVal = c

        ' Determine the maximum of the three numbers
        If b > maxVal Then maxVal = b
        If c > maxVal Then maxVal = c

        ' The median is the remaining value
        Return a + b + c - minVal - maxVal
    End Function

    Sub Main()
        ' Test cases 
        Console.WriteLine("The median of [1, 1, 1] is " &
                          MedianOfThreeNumbers(1, 1, 1))

        Console.WriteLine("The median of [10, 3, 7] is " &
                          MedianOfThreeNumbers(10, 3, 7))

        Console.WriteLine("The median of [10, -10, -10] is " &
                          MedianOfThreeNumbers(10, -10, -10))

        Console.WriteLine("The median of [3, 3, 5] is " &
                          MedianOfThreeNumbers(3, 3, 5))
    End Sub

End Module



' 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
edited Mar 26 by avibootz
...