Implementing "Average" example

and supporting `Stdin.ReadDouble` method.
This commit is contained in:
Dan Buch 2012-12-19 23:23:35 -05:00
parent e0101b4c69
commit 7a40632ca8
3 changed files with 67 additions and 1 deletions

View File

@ -5,7 +5,8 @@ TARGETS := \
$(REPO_BASE)/algs4-flips \ $(REPO_BASE)/algs4-flips \
$(REPO_BASE)/algs4-gcd \ $(REPO_BASE)/algs4-gcd \
$(REPO_BASE)/algs4-rolls \ $(REPO_BASE)/algs4-rolls \
$(REPO_BASE)/algs4-randomseq $(REPO_BASE)/algs4-randomseq \
$(REPO_BASE)/algs4-average
test: build test: build
go test -x $(TARGETS) go test -x $(TARGETS)

View File

@ -0,0 +1,37 @@
package main
import (
"fmt"
"io"
"os"
)
import (
"github.com/meatballhat/box-o-sand/algs4/src/go/algs4"
)
func die(err error) {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
func main() {
sum := 0.0
cnt := 0
for {
d, err := algs4.Stdin.ReadDouble()
if err == io.EOF {
break
}
if err != nil {
die(err)
}
sum += d
cnt++
}
fmt.Printf("Average is %.5f\n", sum/float64(cnt))
}

View File

@ -3,10 +3,38 @@ package algs4
import ( import (
"bufio" "bufio"
"io" "io"
"os"
"strconv" "strconv"
"strings" "strings"
) )
type inputWrapper struct {
Inbuf *bufio.Reader
}
var (
Stdin = &inputWrapper{}
)
func init() {
Stdin.Inbuf = bufio.NewReader(os.Stdin)
}
func (in *inputWrapper) ReadDouble() (float64, error) {
line, err := in.Inbuf.ReadString('\n')
if err != nil {
return float64(0), err
}
dbl, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
if err != nil {
return float64(0), err
}
return dbl, nil
}
func ReadInts(inbuf io.Reader) ([]int, error) { func ReadInts(inbuf io.Reader) ([]int, error) {
ints := make([]int, 0) ints := make([]int, 0)