Newbie problem with variable declarations

Working my way through the code tutorial, stuck at the square root example - can’t figure out why the ‘z’ value being returned by the function is 0. Why is it different from the z being calculated inside the loop?

Thanks!

Here’s the code:

package main

import (
“fmt”
)

func Sqrt(x float64) float64 {
var z float64
var i int
for z:=1.0; i<=10 && zz!=x ; i++ {
z -= (z
z - x) / (2*z)
fmt.Println(x, z)
}
fmt.Println(“result=”)
return z
}

func main() {
fmt.Println(Sqrt(4))
}

1 Like

Could you in future please write proper markup for your code, using a fenced or indented code block?

Aside of that, first you declare var z float64 which initialises with 0.0 as that’s the zero value for floats.

The in the loop you use z := 1.0 which creates a new variable z with its scope limited to the loop. The old z won’t get changed until this z gets out of scope.

Since you never reassign the outer z it stays 0.

You should use = instead of := in the loop when initialising z.

1 Like

Thanks! Will figure out how to stick the code in formatted.

W.r.t. my problem - thanks - I hadn’t absorbed the difference between the assignment formats, that seems clear now…

Thanks, again.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.