2016-04-29 23 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

相关问题