创建具有所需尺寸和值跳过其他所有索引的矩阵的GO函数

发布于 2025-01-22 05:07:57 字数 719 浏览 2 评论 0原文

我正在尝试编写一个创建矩阵的函数,用户可以在其中输入矩阵的尺寸以及其中的值。我设法获得了结果,但我注意到,在输入值时,函数忽略了每两个索引中的一个并用0填充它。

package main

import "fmt"

func makeMatrix(n int, m int) [][]int {
    matrix := make([][]int, n)

    for i := range matrix {
        matrix[i] = make([]int, m)
    }
    fmt.Println("Enter elements : ")
    for i := range matrix {
        fmt.Scanf("%d", &matrix[i])
        for j := range matrix[i] {
            fmt.Scanf("%d", &matrix[i][j])
        }
    }
    fmt.Println(matrix)
    return matrix
}

func main() {
    var (
        n, m int
    )
    fmt.Println("Number of lines : ")
    fmt.Scan(&n)
    fmt.Println("Number of columns: ")
    fmt.Scan(&m)
    makeMatrix(n, m)

}

i'm trying to write a function that creates a matrix where the user can input the dimensions of the matrix as well as the values in it. I managed to get a result but i notice that when it comes to inputting the values the function ignores one of every two indexes and fills it with 0. I'm wracking my head but it doesn't make sense to me...

package main

import "fmt"

func makeMatrix(n int, m int) [][]int {
    matrix := make([][]int, n)

    for i := range matrix {
        matrix[i] = make([]int, m)
    }
    fmt.Println("Enter elements : ")
    for i := range matrix {
        fmt.Scanf("%d", &matrix[i])
        for j := range matrix[i] {
            fmt.Scanf("%d", &matrix[i][j])
        }
    }
    fmt.Println(matrix)
    return matrix
}

func main() {
    var (
        n, m int
    )
    fmt.Println("Number of lines : ")
    fmt.Scan(&n)
    fmt.Println("Number of columns: ")
    fmt.Scan(&m)
    makeMatrix(n, m)

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

予囚 2025-01-29 05:07:57

删除此行&它应该按照您的预期工作。

fmt.scanf(“%d”,& matrix [i])

您已经在matrix [i] [j] [j]上进行scanf,它将读取<<<代码> i &amp; j的每次迭代 - 您无需在matrix [i]上读取/scanf。

Remove this line & it should work as you expected.

fmt.Scanf("%d", &matrix[i])

You are already doing Scanf on matrix[i][j] which will read each iteration of i & each iteration of j - you don't need to read/Scanf on matrix[i].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文