“declared and not used” Error

后端 未结 2 569
独厮守ぢ
独厮守ぢ 2020-12-19 02:49

I get this error saying that I\'m not using a variable… but to my noob eyes, it looks like I am:

func Sqrt(x float64) float64 {

    z := float64(x);
         


        
相关标签:
2条回答
  • 2020-12-19 03:25

    Here is another way to look at the function

    func Sqrt(x float64) (z float64) {
        z = x
        for i := 0; i < 10; i++ {
            z = z - (z*z - x)/(2*z);
        }
        return
    }
    
    0 讨论(0)
  • 2020-12-19 03:30

    The := in your for-loop declares a new variable z which shadows the outer z. Turn it into a plain = to fix the problem.

    func Sqrt(x float64) float64 {
    
        z := x
    
        for i := 0; i < 10; i++ {
            z = z - (z*z - x) / (2 * z);
        }
    
        return z;
    }
    

    By the way, for equal precision and a bit more speed you could try the following implementation which does two of your steps at once:

    func Sqrt(x float64) float64 {
        z := x
        for i := 0; i < 5; i++ {
            a := z + x/z
            z = a/4 + x/a
        }
        return z
     }
    
    0 讨论(0)
提交回复
热议问题