1

好的,我需要通过 msgbox 获取数组的大小和数组输入,并在列表框中显示数组列表,然后获取数组列表的平均值。这是我到目前为止的代码:

Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

    Dim i, size As Integer
    size = Val(InputBox("Please enter array size"))

    Dim sequence(size) As Integer

    'get array values
    i = 0
    Do While i < size
        sequence(i) = Val(InputBox("Please enter element of array"))
        i = i + 1
    Loop

    i = 0
    Do While i < size
        lstoutArray.Items.Add(sequence(i))
        i = i + 1
    Loop
End Sub
4

1 回答 1

2

While something like this will work:

    Dim lstoutArray As New ArrayList
    Dim lstoutCount As Double = 0
    Dim size As Double
    size = Val(InputBox("Please enter array size"))
    For i = 1 To size
        lstoutArray.Add(Val(InputBox("Please enter element of array")))
        lstoutCount += DirectCast(lstoutArray(lstoutArray.Count - 1), Double)
    Next
    Dim lstoutAverage As Double = lstoutCount / lstoutArray.Count

You can see from this example that one of the main drawbacks to using an arraylist, is that it isn't strongly typed. Therefore to use the values in the arraylist you have to cast them as the type you need.

A List(Of) is much easier to use as it's strongly typed already and has the Average extension:

    Dim lstoutArray As New List(Of Double)
    Dim size As Double
    size = Val(InputBox("Please enter array size"))
    For i = 1 To size
        lstoutArray.Add(Val(InputBox("Please enter element of array")))
    Next
    Dim lstoutAverage = lstoutArray.Average
于 2013-10-29T16:05:04.740 回答