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 -= (zz - x) / (2*z)
fmt.Println(x, z)
}
fmt.Println(“result=”)
return z
}
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.