首页 > 解决方案 > 如何在 txt 文件中输出一组数字的平均值?

问题描述

到目前为止我有这个,但它只输出 0

Option Explicit On
Option Strict On
Option Infer Off

Public Class frmMain
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
        Dim inFile As IO.StreamReader
        Dim intBill As Integer
        Dim avg As Integer
        Dim trueAvg As Integer

        If IO.File.Exists("monthlyBills.txt") Then
            inFile = IO.File.OpenText("monthlyBills.txt")
            Do Until inFile.Peek = -1
                Integer.TryParse(inFile.ReadLine, intBill)
                avg += intBill
            Loop
            inFile.Close()
            trueAvg = CInt(avg / 12D)
            lblAvg.Text = trueAvg.ToString()
        Else
            MessageBox.Show("Cannot find the file.", "monthlyBills",
                            MessageBoxButtons.OK, MessageBoxIcon.Information)
            lblAvg.Text = "N/A"
        End If
    End Sub
End Class

这是“monthlyBills.txt”文本文件:

141.71
156.75
179.25
141.71
130.19
115.05
95.65
86.78
85.45
79.99
98.45
126.78

标签: vb.net

解决方案


要使用没有 a 的方法,.TryParse您必须非常确定文本文件中的每一行都是一个数字。

.ReadAllLines返回一个数组,其中每个元素都是文本文件中的一行。

接下来我们使用一点 Linq 将每一行(它是一个字符串)更改为一个 Decimal 值。删除可能存在的.Trim任何空白。不用担心IEnumerable。这就是这个 Linq 返回的内容。这只是意味着您可以通过循环遍历它For Each

然后我们就可以调用上的.Average方法IEnumerable,我们就完成了。

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    Dim lines As String() = File.ReadAllLines("monthlyBills.txt")
    Dim decs As IEnumerable(Of Decimal) = From line In lines
                                          Select CDec(line.Trim)
    Dim avg As Decimal = decs.Average
    lblAvg.Text = avg.ToString("N2")
End Sub

这是另一个不使用 Linq 查询但使用 .TryParse 的示例。如果您使用 List 而不是数组,则不必提前知道要添加多少项。此外,您不需要跟踪索引。您仍然使用列表中的 .Average 方法。

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    Dim lines As String() = File.ReadAllLines("monthlyBills.txt")
    Dim decs As New List(Of Decimal)
    Dim dec As Decimal

    For Each line As String In lines
        If Decimal.TryParse(line, dec) Then
            decs.Add(dec)
        Else
            MessageBox.Show(line & " is not a number and is being excluded from calculations.")
        End If
    Next

    Dim avg As Decimal = decs.Average
    lblAvg.Text = avg.ToString("N2")
End Sub

推荐阅读