Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。
2个月前关闭。
Improve this question
我必须编写一个程序以根据数组编号打印条形图,示例应如下所示:
想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。
2个月前关闭。
Improve this question
我必须编写一个程序以根据数组编号打印条形图,示例应如下所示:
|
| |
| | |
| | |
| | | |
| | | | |
1 4 5 6 2
我一直在尝试,当我使用fmt.Println()时,所有循环每行显示一行|
1
|
|
|
|
4
|
|
|
|
|
5
|
|
|
|
|
|
6
|
|
2
这是我的代码package main
import "fmt"
func main(){
var number = []int{1, 4, 5, 6, 2}
for i, element := range number {
for i = 0; i < element; i++ {
fmt.Println("|")
}
fmt.Println(element)
}
}
最佳答案
生成直方图:
package main
import (
"fmt"
"math"
)
func main() {
var array = []int{1, 4, 5, 6, 2, 10, 4, 2, 1, 0, 10}
max := math.MinInt64
// Find the maximum to determine the suitable grid to plot
// the histogram
for _, e := range array {
if e > max {
max = e
}
}
var (
row = max
col = len(array)
)
// Create a grid of dimension [row * col]
// Allocate rows
histogram := make([][]string, row)
for i := 0; i < row; i++ {
// Allocate columns for each row
histogram[i] = make([]string, col)
}
// Histogram formation logic
// Use blank spaces (" ") or " | " to fill the grid
for i, e := range array {
for j := row - 1; j >= 0; j-- {
if j >= row-e {
histogram[j][i] = " | "
} else {
histogram[j][i] = " "
}
}
}
// Print the histogram
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
fmt.Printf("%s", histogram[i][j])
}
fmt.Printf("\n")
}
// Careful when printing numbers. Pretty printing happens
// for single digit number. When the digits of the number increase,
// make sure to put a custom logic to do the proper calculated
// based on digit of the number.
for i := 0; i < col; i++ {
fmt.Printf(" %d ", array[i])
}
fmt.Printf("\n")
}
输出: |
| |
| | |
| | |
| | | |
| | | | |
1 4 5 6 2