为什么 fmt.Printf 交换行?

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

why does fmt.Printf swap rows?

问题

我最近开始学习Golang,但我没有太多的编程经验。在学习for循环和Math.Pow函数时,我遇到了一个问题。有人可以解释一下为什么在这个循环中,第二行(3, 3, 20)先被计算,然后才计算第一行(3, 2, 10)吗?而且,还给它分配了一个限制。如果有人能解释一下,我将非常感激。

我预期程序的输出应该是这样的:

9
27>=20
英文:

I recently started learning Golang and I don't have much programming experience. I ran into a problem while learning the for loop and the Math.Pow.(Tour of Go) function. Can someone explain why in this loop the second row (3, 3, 20) is counted first, and only then it counts the first (3, 2, 10). Moreover, a limit is also attributed to him. I would be very grateful if someone could clarify.

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),
	)
}

// Output:
// 27 >= 20
// 9 20

I expected the output of the program to look like this.

9
27>=20

答案1

得分: 2

Println的参数从左到右进行求值,所以你的调用

fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
)

实际上变成了:

fmt.Println(
        9,
        20,
)

但除此之外,第二次调用pow(返回20)还调用了自己的Printf("27>=20"),所以你得到的结果实际上是明确定义且符合预期的。

英文:

Arguments of Println are evaluated from left-to-right, so your call

fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
)

effectively becomes:

fmt.Println(
        9,
        20,
)

But in addition to that, second call to pow (that returned 20) called Printf on it's own ("27>=20"), so the result that you got is actually well-defined and expected.

huangapple
  • 本文由 发表于 2023年6月22日 19:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531284.html
匿名

发表评论

匿名网友

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

确定