英文:
%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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论