user3059116
user3059116

Reputation: 3

Why won't my output display as a decimal?

So I have this program that takes the values of items in a listbox and puts them into an array. The only problem I have is that when there is an even amount of numbers in the listbox, it should add up the two values and divide it by two to find the median. For some reason, it refuses to output it as a decimal, just puts out an integer. I've tried to change all the values to decimals, but that only created a error, telling me that 'Option strict prevents conversions from long to decimal' or something like that (I need Op stric on). Could anyone tell me why my output isn't coming out as a decimal??

    Dim arrNumbers(lstNumbers.Items.Count), intLength, intNum1, intNum2 As Integer
    Dim decMedian As Decimal


    For i = 0 To lstNumbers.Items.Count - 1

        arrNumbers(i) = CInt(lstNumbers.Items(i))
    Next

    intLength = arrNumbers.Length - 1

    Array.Sort(arrNumbers)


    If intLength Mod 2 <> 0 Then
        MessageBox.Show("Median =" & arrNumbers(arrNumbers.GetUpperBound(0) \ 2 + 1).ToString)

    Else


        intNum1 = arrNumbers(arrNumbers.GetUpperBound(0) \ 2)

        intNum2 = arrNumbers((arrNumbers.GetUpperBound(0) \ 2) + 1)

        decMedian = (intNum1 + intNum2) \ 2

        MessageBox.Show("Median =" & decMedian.ToString("n2"))
    End If

Upvotes: 0

Views: 364

Answers (1)

Szymon
Szymon

Reputation: 43023

Replace

decMedian = (intNum1 + intNum2) \ 2

with

decMedian = (intNum1 + intNum2) / 2

\ is the integer division operator. Check more on MSDN.

Upvotes: 4

Related Questions