vb.net 如何计算数组列表的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19655914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I Calculate the Average of the Array List
提问by Alan Broderick
Ok I need to get size of the array and the array inputs through a msgbox and display the array list in a list box and then get the average of the array list. here is the code I have so far:
好的,我需要通过 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
回答by tinstaafl
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 Averageextension:
List(Of) 更容易使用,因为它已经是强类型的并且具有Average扩展名:
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

