locked
What's the easiest way to do this? RRS feed

  • Question

  • Suppose I have the following list of pre-defined numbers: 5,10,15,20,25,30,40,50,60,80 & 100.  These numbers represent available speed ratios for gearboxes that we use in the equipment that we manufacture.  I need to take a decimal number that is calculated from other parameters & find which of the numbers above it's closest to.  For example, if I have 38.175 I need to use 40, 26.365 needs to use 25, etc.  So what is the easiest/best way to do this?  Firstly, where should I store the pre-defined numbers ... in an array perhaps?  Secondly, how do I compare the calculated decimal number to the pre-defined numbers & pick the closest one?  Any ideas or help would be greatly appreciated.  Thanks...

    Thursday, July 20, 2006 3:38 PM

Answers

  • try this out and see if it works for ya:

    Dim PredefinedNumbers() As Integer = {5, 10, 15, 20, 25, 30, 40, 50, 60, 80, 100}

    Private Function GetCLosestPredefinedNumber(ByVal d As Decimal) As Integer

    Array.Sort(PredefinedNumbers)

    Select Case True

    Case d < PredefinedNumbers(0)

    Return PredefinedNumbers(0)

    Case d > PredefinedNumbers(PredefinedNumbers.Length - 1)

    Return PredefinedNumbers(PredefinedNumbers.Length - 1)

    Case Else

    For x As Integer = 0 To PredefinedNumbers.Length - 2

    If d = PredefinedNumbers(x) Then

    Return PredefinedNumbers(x)

    End If

    If d > PredefinedNumbers(x) AndAlso d < PredefinedNumbers(x + 1) Then

    If ( d-PredefinedNumbers(x) ) > (PredefinedNumbers(x + 1) - d) Then

    Return PredefinedNumbers(x + 1)

    Else

    Return PredefinedNumbers(x)

    End If

    End If

    Next

    End Select

    End Function

    Thursday, July 20, 2006 4:31 PM