MadsTheMan - 1 year ago 62

Vb.net Question

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

`Dailyfile`

`AverageFile`

`average`

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`

I've tried a bunch of variations on the

`total 0= double.parse(line)`

`diming the total as integer = 0`

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