如何计算阵列的平均值?

时间:2016-05-17 09:35:22

标签: vb.net

 Public Class Form1
Dim x As Integer
Dim y(9) As Double
Dim average As Double
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For x = 0 To 9
        y(x) = x
    Next
    average = y(9) / 10
    Label1.Text = average
End Sub
End Class

我在尝试计算0到9数组的平均值时遇到了麻烦,我意识到我的代码只计算9除以10,我如何继续计算10个数的平均值?

3 个答案:

答案 0 :(得分:3)

使用Linq ......

Dim average As Double = y.Average()

您可以使用Linq做的另一件事是从平均值中排除某些值。以此示例将myNumbers()中的9个项目设置为10,然后将第10个项目设置为零。我使用Linq首先过滤大于零的数字,然后执行Average聚合。

Dim myNumbers(9) As Double
For i As Integer = 0 To 8 Step 1
    myNumbers(i) = 10
Next i

myNumbers(9) = 0

Dim average As Double = myNumbers.Where(Function(num) num > 0).Average()
'Optionally, you could also do it this way:
Dim average2 As Double = (From num In myNumbers
                          Where num > 0).Average()
MessageBox.Show(average)

使用类时会更好。考虑这个班级Thing

Public Class Thing
 Public Name As String = ""
 Public Number As Double = 0

 Public Sub New (name As String, number As Double)
    Me.Name= name
    Me.Number = number
 End Sub
End Class 

我可以创建该类的集合,.Where变得更加强大。在此示例中,我按Thing.Number

平均Thing.Name
Dim things As List(Of Thing) = New List(Of Thing)()
things.Add(New Thing("Michael", 10))
things.Add(New Thing("Michael", 5))
things.Add(New Thing("Michael", 7))
things.Add(New Thing("Michael", 9))
things.Add(New Thing("Rian", 10))
things.Add(New Thing("Rian", 10))
things.Add(New Thing("Rian", 10))

Dim AverageMichael As Double = things.Where(Function(thing) thing.Name = "Michael").Average(Function(thing) thing.Number)
Dim AverageRian As Double = things.Where(Function(thing) thing.Name = "Rian").Average(Function(thing) thing.Number)

MessageBox.Show(AverageMichael)
MessageBox.Show(AverageRian)

附注
如果您是.NET开发人员,并且您想学习使用Linq,或者您只需要一个简单的环境来测试.NET代码,那么我强烈推荐使用LinqPad。我使用LinqPad获取本文中的所有代码。

http://www.linqpad.net/

答案 1 :(得分:1)

一组值的平均值等于值的总和除以值的数量。 您需要声明变量 sum 以添加数组的每个值,然后除以10.

答案 2 :(得分:1)

您需要将所有值相加然后除以。我建议使用一个简单的函数:

Function getAverage(y As Double()) As Double
    Dim z As Double
    For Each i As Double In y
        z += i
    Next
    Return z / y.Length
End Function

只需将平均值设置为getAverage(y)

即可