%d golang, how do you add spaces between Prints?

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

%d golang, how do you add spaces between Prints?

问题

我有一个与golang动词相关的问题,特别是**%d**。在这种情况下,我有**"%4d",我无法理解它是如何打印出空格的,实际上在打印较大的数字时会减小空间大小**,就像在最后一行中的两位数(3个空格)和一位数中打印4个空格的情况一样。

for _, line := range s {
    for _, value := range line {
        fmt.Printf("%4d ", value)
    }
    fmt.Println()
}

$ go run main.go 5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

英文:

I have question related to golang verbs, especially %d. In this case I have "%4d " that I can't understand how does it prints the empty space that actually reduces in size when printing bigger numbers like in the last line with 2 digit numbers (3 empty spaces) and with 1 digit numbers where it prints 4 empty spaces?

for _, line := range s {
	for _, value := range line {
		fmt.Printf("%4d ", value)
	}
	fmt.Println()
}

$ go run main.go 5
   1    2    3    4    5
   2    4    6    8   10
   3    6    9   12   15
   4    8   12   16   20
   5   10   15   20   25

答案1

得分: 6

根据fmt包的文档说明:

> 对于大多数值,宽度是输出的最小符文数,如果需要的话,用空格填充格式化形式。

在你的情况下,它输出至少4个符文,并根据需要进行填充。%04d会用零进行填充。

英文:

As the documentation for the fmt package states:

> For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

In your case, it outputs a minimum of 4 runes, padding as necessary. %04d would pad with zeros.

huangapple
  • 本文由 发表于 2022年7月25日 00:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73100338.html
匿名

发表评论

匿名网友

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

确定