如何找到文本文件中所有数字的平均值

时间:2016-04-29 11:24:25

标签: vb.net average

我可笑地坚持这个。我的下面的代码总结了文本文件Dailyfile中的所有数字,并将总数输出到AverageFile。问题是我不想总结。我想让它找出所有数字的average

我该怎么做?

Dim AverageFile As String = "C:\xxx\zzz\" & System.DateTime.Now.ToString("yyyyMMdd") & ".txt"
Dim DailyFile As String = "C:\xxx\xxx\" & System.DateTime.Now.ToString("yyyyMMdd") & ".txt"  

            Try
                If System.IO.File.Exists(AverageFile) Then
                    Dim total As double = 0
                    For Each line As String In IO.File.ReadAllLines(DailyFile)

                        total += Double.Parse(line)
                    Next
                    Dim objWriter As New System.IO.StreamWriter(AverageFile, false)
                    objWriter.WriteLine(total.ToString) 
                    objWriter.Close()
                Else
                    'Nothing yet
                End If

            Catch ex As Exception
                lbErrors.Items.Add(String.Concat(TimeOfDay & " Error 98: File or folder might not exist. Restart application... ", ex.Message))
            End Try

Dailyfile看起来像这样;

enter image description here

我在total 0= double.parse(line)尝试了很多变种,因为我觉得这就是问题所在。我也试过diming the total as integer = 0。我是计算的新手,所以我不知道事情是怎么回事。

2 个答案:

答案 0 :(得分:3)

平均值只是总数除以总结的数量。 (假设你想使用arithmetic mean,这可能就是你要找的。)

Dim total As double = 0
Dim numOfLines As Integer = 0
For Each line As String In IO.File.ReadAllLines(DailyFile)
    numOfLines += 1
    total += Double.Parse(line)
Next
Dim average As Double = total / numOfLines
Dim objWriter As New System.IO.StreamWriter(AverageFile, false)
objWriter.WriteLine(average.ToString) 
objWriter.Close()

代码中缺少的只是跟踪行数并将总和除以此数字。

仅作为一个例子:我们是3个人。我今年23岁,你今年35岁,我们的朋友是40岁。我们年龄的平均值为(23 + 35 + 40) / 3,即32.666 ......

答案 1 :(得分:3)

使用CherryDT's approach计算行数并将总数除以此数字或使用LINQ的Enumerable.Average,例如使用此简明查询:

Dim allNumbers = From line In IO.File.ReadLines(DailyFile)
                 Let num = line.TryGetDouble()
                 Where num.HasValue
                 Select num.Value
Dim average As Double = allNumbers.Average()

我已使用以下extension method尝试将字符串解析为Nullable(Of Double)

Imports System.Runtime.CompilerServices

Module StringExtensions
    <Extension()>
    Public Function TryGetDouble(ByVal str As String) As Nullable(Of Double)
        If str Is Nothing Then Return Nothing
        Dim d As Double
        If Double.TryParse(str.Trim(), d) Then
            Return d
        Else
            Return Nothing
        End If
    End Function
End Module