MadsTheMan MadsTheMan - 1 year ago 70 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

and outputs the total to
. The problem is I don't want it to sum up. I want it to find out the
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"

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)
Dim objWriter As New System.IO.StreamWriter(AverageFile, false)
'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

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 Source

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)
Dim average As Double = total / numOfLines
Dim objWriter As New System.IO.StreamWriter(AverageFile, false)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download