Skip to content

tour: unclear instruction for errors exercise #273

@adderek

Description

@adderek

Context: https://tour.golang.org/methods/20

The instruction does not clearly define what to do.
I was expecting an output:

1.41
cannot Sqrt negative number: -2

while the only output I was able to produce is

1.41 <nil>
0 cannot Sqrt negative number: -2

as fmt.Println(Sqrt(2)) will print "error"
and fmt.Println(Sqrt(-2)) will print the float64 part

It should be also noted earlier that %g is the way to print float64

My code:

type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
	return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func (e ErrNegativeSqrt) String() string {
	return fmt.Sprintf("%f",e)
}
func Sqrt(x float64) /*ErrNegativeSqrt*/(float64, error) {
	if x<0 {
		return 0,ErrNegativeSqrt(x) // Why do I need to include 0? nil seems more appropriate
	}
	var z1, z2 float64 = 1,0
	for i:=0; i<8; i++ {
		z2 = z1-((z1*z1-x)/(2*z1))
		z1=z2
	}
	return z2, nil
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions