如何在数组(5,2)中添加10个值,然后计算它们的平均值

时间:2014-11-10 03:46:06

标签: vb.net

假设有5条记录,每条记录都包含温度值。每个记录的第一个温度值代表气象站的高温,每个记录的第二个温度代表气象站的低温,将这些温度输入表TEMP(5,2),高温来自气象站。表格第1栏中的电台,以及表格第2栏中5个电台的低温。在读取所有温度后,找到并输出5个气象站的平均高温和平均低温。

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用2D数组和字典

使用词典

Dim temArray As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)() '<-- declaration of dictionary 
'<--- you can get all these values from the user also
temArray.Add(31, 20)'<-- add first set of high and low temperature values
temArray.Add(28, 17)'<-- add second set of high and low temperature values
temArray.Add(27, 16)'<-- add third set of high and low temperature values
temArray.Add(22, 19)'<-- add fourth set of high and low temperature values
temArray.Add(30, 22)'<-- add fifth set of high and low temperature values
Dim avgHighTemp As Double = temArray.Keys.Sum() / 5 '<-- average high temperature 27.6
Dim avgLowTemp As Double = temArray.Values.Sum() / 5'<-- average high temperature 16.8

使用2D数组

    Dim temArray(,) As Integer = New Integer(4, 1) {{31, 20}, {28, 17}, {22, 19}, {30, 22}, {27, 6}}
    Dim avgHighTemp As Double = 0
    Dim avgLowTemp As Double = 0
    For i As Integer = 0 To 4
        avgHighTemp += temArray(i, 0)
        avgLowTemp += temArray(i, 1)
    Next
    MsgBox("Average high temperature :" & avgHighTemp / 5)
    MsgBox("Average high temperature :" & avgLowTemp / 5)