打印以表格形式呈现的数据。

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

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

https://go.dev/play/p/_u5W46AZ5sq

huangapple
  • 本文由 发表于 2022年1月9日 04:33:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/70636203.html
匿名

发表评论

匿名网友

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

确定