vb.net - 如何在 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
解决方案
要使用没有 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
推荐阅读
- spring - @OneToOne(cascade = {CascadeType.ALL}) 问题
- postgresql - 如何在 PostgreSQL 中执行 FULL JOIN、LEFT JOIN 和 RIGHT JOIN
- node.js - 如何访问结果视频中的数据?(柏)
- python - 使用 Python 进行二维热传导
- python - 5个最常见项目的条形图
- ninja - 忍者能处理长文件名吗?
- r - (自动)在 RStudio 控制台中以各自的颜色显示十六进制字符串?
- python - 如何获取for循环内的文本长度
- php - Zammad API:使用标签创建票证
- amazon-web-services - 如何在 API Gateway (AWS) 的资源策略中使用与 API 密钥关联的标签