2016-04-29 64 views
3

我在這個問題上被卡住了。我的代碼總結了文本文件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

嘗試'File.ReadAllLines(路徑)。選擇(double.Parse)。平均()'。 – Enigmativity

回答

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 ...

+0

謝謝,CherryDT。這實際上正是我所錯過的。 – MadsTheMan

+0

有點遲來這個,但有沒有任何小的調整,以便我只得到例如32作爲輸出,而不是32.666? – MadsTheMan

+1

如果你真的想總是舍入(如你的例子),你可以在末尾使用'Math.floor(average)'而不是'average'(例如'objWriter.WriteLine(Math.floor(average).ToString )')。如果要使用銀行家舍入(即32.4將變爲32,但32.6將變爲33),請使用'Math.round(average,0)'。 – CherryDT

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 
+0

感謝您的回答,並詳細介紹了Tim。我正在抓住你交給我的知識,我將探索這種可能性。 – MadsTheMan

相關問題