《Go之旅#23:返回值的奇怪行为》

huangapple go评论64阅读模式
英文:

A Tour of Go #23: weird behaviour with return

问题

这段代码是一个简单的Go语言程序,它定义了一个名为pow的函数,用于计算给定数字的幂。在main函数中,调用了两次pow函数,并打印出结果。

在第一次调用pow函数时,传入的参数是3、2和10。在函数内部,使用math.Pow函数计算3的2次幂,并将结果赋值给变量v。然后,通过比较vlim的大小,判断是否返回v或打印一条消息。由于27大于等于20,所以会打印出27 >= 20。然后,返回lim的值,即10。

在第二次调用pow函数时,传入的参数是3、3和20。同样地,计算3的3次幂,并将结果赋值给v。由于27大于等于20,所以会打印出27 >= 20。然后,返回lim的值,即20。

如果将return v这一行注释掉,那么在第一次调用pow函数时,不会返回v的值。因此,第一次调用的结果是10,而不是27。第二次调用的结果仍然是20。

这是因为在第一次调用pow函数时,虽然计算出了27,但由于没有返回该值,所以在打印结果时并没有使用该值。因此,第一次调用的结果并不是27,而是10。

英文:

A Tour of Go #23:

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
        
    } else {
        fmt.Printf("%g >= %g\n", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

The results are:

27 >= 20
9 20

If I comment out the return v line, the results are:

27 >= 20
10 20

Why exactly does this happen? Why are results of the first pow() call not equal to 27 >= 20 and 10?

答案1

得分: 1

如@larsmans已经回答的那样,你在第一个调用中传递了一个限制为10的参数,因此返回的数字是10而不是20。

将其更改为:

func main() {
    fmt.Println(
        pow(3, 2, 20),
        pow(3, 3, 20),
    )
}

当删除return v行时,你将看到以下输出:

27 >= 20
20 20
英文:

As already answered by @larsmans, you're passing a limit of 10 to the first call, thus
the returned number is 10 instead of 20.

Change it to

func main() {
    fmt.Println(
        pow(3, 2, 20),
        pow(3, 3, 20),
    )
}

And you will see the following output when removing the return v line:

27 >= 20
20 20

huangapple
  • 本文由 发表于 2013年10月10日 21:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/19297736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定