dongtu1958 2017-05-22 14:58
浏览 374
已采纳

在Golang中随机生成矩阵

I'm currently writing a program and I want to randomly generate a matrix.

Currently I'm pre-setting the values in it as follows:

    m1 := [3][3]int{
    [3]int{1, 1, 1},
    [3]int{4, 1, 7},
    [3]int{1, 65, 1},
}

However I want the values inputted to be randomly generated in a range from 1-100.

import "math/rand"

I am importing the above library and trying to utilise it.

I have attempted to get this working however can't seem to make any headway.

    m1 := [3][3]int{
    [3]int{rand.Intn, 1, 1},
    [3]int{4, 1, 7},
    [3]int{1, 65, 1},
}

I have attempted to complete it with the above solution to make the first number random however I get the following error.

cannot use rand.Intn (type func(int) int) as type int in array or slice literal

Any help greatly appreciated.

  • 写回答

2条回答 默认 最新

  • douhuigang9550 2017-05-22 15:04
    关注

    The direct answer is the fact that rand.Intn() generates a random integer between 0 and n, where n is a parameter to this method. The error that you are getting is the compiler complaining that you are trying to initialize an int value with a function that requires two ints and returns one - you are trying to assign a function to an int. So the correct call would be something like rand.Intn(100), which will give you a random number between 0 - 100.

    However, why do it this way? Why not dynamically initialize your array with random numbers as:

    m1 := [3][3]int{}
    for i:=0; i<3; i++ {
        for j:=0; j<3; j++ {
            m1[i][j] = rand.Int()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?