var数组[行] [列] int在Go中将维度分配给数组

问题描述 投票:0回答:1

晚安。我是新来的。这是我在GO中的代码。

package main

import ( "fmt" )

func main() { var number int fmt.Print("how many candidates?: ") fmt.Scanf("%v\n", &number) fmt.Print(numero)

var name []string
var nameHorse []string
var matrix [][]int

for i := 0; i < number; i++ {
    fmt.Print("name: ")
    fmt.Scanf("%v\n", &name[i])
    fmt.Print("name horse: ")
    fmt.Scanf("%v\n", &nameHorse[i])
    for j := 0; j < 3; j++ {
        fmt.Print("how many minutes: ")
        fmt.Scanf("%v\n", &matrix[i][0])
        fmt.Print("how many segs: ")
        fmt.Scanf("%v\n", &matrix[i][1])
        fmt.Print("hoy many h: ")
        fmt.Scanf("%v\n", &matrix[i][2])
    }
}

for i := 0; i < number; i++ {
    fmt.Print(name[i])
    fmt.Print(nameHorse[i])
    for j := 0; j < 3; j++ {
        fmt.Print(matrix[i][j])
    }
    fmt.Print()
}
}

i want to difine an array [2][4] but i want to difine when the program is ON, like this:

fmt.Print("rows: ") fmt.Scanf("%v\n", &rows)

fmt.Print("columnas: ") fmt.Scanf("%v\n", &columns)

var matrix [rows][columns]int

我想为将控制台将值引入矩阵的项目添加尺寸。

有人可以帮我,我该怎么做?

arrays for-loop go matrix multidimensional-array
1个回答
0
投票

如果您在编译时不知道大小,则必须使用slice;对于多维,则需要使用循环:

matrix := make([][]int, rows)
for i := 0; i < rows; i++ {
    matrix[i] = make([]int, columns)
}
© www.soinside.com 2019 - 2024. All rights reserved.