From 411e266c4d04b7acec3dbff40be7341aecb08f15 Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Tue, 28 Aug 2012 21:35:32 -0600 Subject: [PATCH] added argv support to the sqrt program --- exercises/00-sqrt/go.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/exercises/00-sqrt/go.go b/exercises/00-sqrt/go.go index 6a9f8e9..972ce38 100644 --- a/exercises/00-sqrt/go.go +++ b/exercises/00-sqrt/go.go @@ -3,8 +3,11 @@ package main import ( "fmt" "math" + "os" + "strconv" ) +const usage = "usage: sqrt " const min_threshold = 1e-200 type ErrNegativeSqrt float64 @@ -32,16 +35,24 @@ func Sqrt(x float64, threshold float64) (z float64, iterations int, err error) { } func main() { + if len(os.Args) != 2 { + fmt.Fprintf(os.Stderr, "%v\n", usage) + os.Exit(1) + } + i, err := strconv.ParseFloat(os.Args[1], 32) + if err != nil { + panic(err) + } threshold := 1.0 - right_answer := math.Sqrt(2) + right_answer := math.Sqrt(i) for threshold > min_threshold { - answer, iterations, err := Sqrt(2, threshold) + answer, iterations, err := Sqrt(i, threshold) if err != nil { panic(err) } - fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n", - threshold, right_answer-answer, right_answer, answer, - iterations) + fmt.Printf("%0.4g %0.2d %0.20f %0.20f %0.4g\n", + threshold, iterations, right_answer, answer, + right_answer-answer) threshold = threshold / 10.0 } }