doushu8260 2019-01-26 21:32
浏览 24
已采纳

为什么从这个简单的Go代码中得到这样的输出?

I am new to Go and very confused with one of the sample codes in the tutorial. Here is the code and its output:

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
", v, lim)
    }
    return lim
}

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

When I run it, the output of this code is:

27 >= 10
64 >= 20
10 20

Which is quite strange to me! I expect this output:

27 >= 10
10
64 >= 20
20

Can someone please help me to understand what is going on with Println in this code?

  • 写回答

1条回答 默认 最新

  • dongzen2675 2019-01-27 02:59
    关注

    In Go, as in the vast majority of modern programming languages, the arguments of a function call are evaluated before the function call itself. Consider the following function:

    func add(i, j int) int {
      return i + j
    }
    

    And let's call it like this:

    func a() int {
      return 2
    }
    
    func b() int {
      return 3
    }
    
    // ... somewhere in main()
    add(a(), b())
    

    You would expect that, by the time the code of add runs, the values of i and j are known, right? The call would then return 5 as expected. To enable this, the Go compiler arranges for the arguments of add - namely a() and b() to be run before add itself runs.


    The same happens in your code sample with Println and pow. The arguments to Println need to be evaluated before its body is run, and evaluating pow causes other things to be printed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大