trying_out_go/averageMySolution.go

38 lines
699 B
Go
Raw Normal View History

2023-10-16 12:44:08 -04:00
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"git.linuxhg.com/john-okeefe/keyboard"
)
2023-10-18 20:46:25 -04:00
func averageMySolution() {
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)
2023-10-16 12:44:08 -04:00
var sum float64 = 0
scanner := bufio.NewScanner(file)
counter := 0
for scanner.Scan() {
number, err := strconv.ParseFloat(scanner.Text(), 64)
Error(err)
2023-10-16 12:44:08 -04:00
sum += number
counter++
}
err = file.Close()
Error(err)
if scanner.Err() != nil {
log.Fatal(scanner.Err())
2023-10-16 12:44:08 -04:00
}
sampleCount := float64(counter)
2023-10-16 12:44:08 -04:00
fmt.Printf("Average: %0.2f\n", sum/sampleCount)
}