average.go updated to process a file of numbers provide via commandline
This commit is contained in:
parent
50567bc93e
commit
af6ae12947
39
average.go
39
average.go
@ -1,13 +1,44 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.linuxhg.com/john-okeefe/keyboard"
|
||||
)
|
||||
|
||||
func Error(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func average() {
|
||||
numbers := [3]float64{71.8, 56.2, 89.5}
|
||||
fmt.Printf("What is the name of the file: ")
|
||||
fileString, err := keyboard.GetString()
|
||||
Error(err)
|
||||
fileString = strings.TrimSpace(fileString)
|
||||
file, err := os.Open(fileString)
|
||||
Error(err)
|
||||
var sum float64 = 0
|
||||
for _, number := range numbers {
|
||||
scanner := bufio.NewScanner(file)
|
||||
counter := 0
|
||||
for scanner.Scan() {
|
||||
number, err := strconv.ParseFloat(scanner.Text(), 64)
|
||||
Error(err)
|
||||
sum += number
|
||||
counter++
|
||||
}
|
||||
sampleCount := float64(len(numbers))
|
||||
err = file.Close()
|
||||
Error(err)
|
||||
if scanner.Err() != nil {
|
||||
log.Fatal(scanner.Err())
|
||||
}
|
||||
sampleCount := float64(counter)
|
||||
fmt.Printf("Average: %0.2f\n", sum/sampleCount)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user