英文:
Print data in form of table
问题
我有一段代码,它将值打印到3列,但我无法将它们打印成直列。
fmt.Printf("%d | %.1f | %.5f | \n", int(i), x, val)
我得到的输出是这样的:
0 | 0.0 | error |
1 | 90.0 | error |
2 | 180.0 | -0.00000 |
3 | 270.0 | 3.94795 |
4 | 360.0 | error |
5 | 450.0 | error |
6 | 540.0 | -0.00000 |
7 | 630.0 | 3.94795 |
8 | 720.0 | error |
我找不到在Go语言中实现这个的方法。
英文:
I have a code, that prints values to 3 columns, but i can't print them in straight columns
fmt.Printf("%d | %.1f | %.5f | \n", int(i), x, val)
I'm getting this:
0 | 0.0 | error |
1 | 90.0 | error |
2 | 180.0 | -0.00000 |
3 | 270.0 | 3.94795 |
4 | 360.0 | error |
5 | 450.0 | error |
6 | 540.0 | -0.00000 |
7 | 630.0 | 3.94795 |
8 | 720.0 | error |
I couldn't find a way to do this in go.
答案1
得分: 5
你可以查看 tabwriter。
tabwriter 包实现了一个写入过滤器(tabwriter.Writer),将输入中的制表符列转换为正确对齐的文本。
package main
import (
"fmt"
"os"
"text/tabwriter"
)
func main() {
w := tabwriter.NewWriter(os.Stdout, 10, 1, 1, ' ', tabwriter.Debug)
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 0, 0.0, "error")
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 0, 90.0, "error")
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 7, 630.0, 3.94795)
w.Flush()
}
https://go.dev/play/p/_u5W46AZ5sq
英文:
You can look at tabwriter
> Package tabwriter implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text.
package main
import (
"fmt"
"os"
"text/tabwriter"
)
func main() {
w := tabwriter.NewWriter(os.Stdout, 10, 1, 1, ' ', tabwriter.Debug)
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 0, 0.0, "error")
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 0, 90.0, "error")
fmt.Fprintf(w, "%d\t%v\t%v\t\n", 7, 630.0, 3.94795)
w.Flush()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论