trying_out_go/playground/averageMySolution.go

38 lines
699 B
Go

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