如何计算阵列的平均值?

时间:2017-05-23 21:01:20

标签: vb.net

给定一个整数数组,如何在VB.NET中计算该数组的平均值?

数组初始化如下:

Public Class Form1        
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click    
        Dim numbers() As Integer = {1, 2, 3, 4, 5}
    End Sub
End Class

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。他们都很容易。这是两个。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim numbers() As Integer = {1, 2, 3, 4, 5, 6}
    Dim sum As Integer = 0

    'method 1 - more or less the way you'd do it by hand
    For Each n In numbers
        sum += n
    Next
    Dim average As Double = sum / numbers.Length
    MessageBox.Show(average.ToString())

    'method 2 - just use the array's extension method
    MessageBox.Show(numbers.Average())
End Sub

答案 1 :(得分:0)

我将如何做到这一点。

Private Sub Button1_Click(autogenerated stuff) Handles Button1.Click
   Dim numbers() As Integer = {1, 2, 3, 4, 5, 6}
   Dim Average As Integer

'add up all numbers in array (the number in parentheses is the index, which starts at 0)
   Average = (numbers(0) + numbers(1) + numbers(2) + numbers(3) + numbers(4) _
              + numbers(5)) / 6

然后,根据您是要在标签还是消息框中显示它,您可以使用

Me.Label1.Text = "The average of these numbers is " & Average

MessageBox.Show("The average of these numbers is " & Average)