MadsTheMan MadsTheMan - 7 months ago 20
Vb.net Question

How can Ι find the average of all numbers in a textfile

I'm ridiculously stuck on this one. My code below sums up all the numbers that are in the textfile

Dailyfile
and outputs the total to
AverageFile
. The problem is I don't want it to sum up. I want it to find out the
average
of all the numbers.

How can I do this?

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


The
Dailyfile
simply looks like this;

enter image description here

I've tried a bunch of variations on the
total 0= double.parse(line)
, because I feel like thats where the problem lies. I've also tried
diming the total as integer = 0
. I'm new to the calculating, so I don't know how things go.

Answer

The average is just the total divided by the number of things you summed up. (Assuming you want to use the arithmetic mean, which is probably what you are looking for.)

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()

What was missing in your code is just keeping track of the number of lines and dividing the sum by this number.


Just as an example: We are 3 people. I am 23 years old, you are 35 years old, our friend is 40 years old. The average of our ages would be (23 + 35 + 40) / 3 which is 32.666...

Comments