From af6ae12947a0b6667f778405173b28619ef74fdf Mon Sep 17 00:00:00 2001 From: John O'Keefe Date: Tue, 17 Oct 2023 17:49:18 -0400 Subject: [PATCH] average.go updated to process a file of numbers provide via commandline --- average.go | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/average.go b/average.go index 67cf79c..192dbdd 100644 --- a/average.go +++ b/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) }