“已声明且未使用"错误 [英] "declared and not used" Error

查看:48
本文介绍了“已声明且未使用"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误消息,说我没有使用变量….但是在我的菜鸟眼中,看起来我是:

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);

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

    return z;
}

有人能指出我对语言的缺失吗?我认为这与=:=和作用域有关,但我不确定.

Can anyone point out what I'm missing about the language? I think it has to do with = vs. := and scoping, but I'm not sure.

推荐答案

for循环中的:=声明了一个新变量z,该变量遮盖了外部z.将其变成普通的=即可解决问题.

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
 }

这篇关于“已声明且未使用"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆