【问题标题】:Generating random matrix in c [closed]在c中生成随机矩阵
【发布时间】:2012-11-27 17:00:34
【问题描述】:

所以我得到的程序是从矩阵中的每一行中找到最大值,现在如何生成随机矩阵,例如:n 长度和 m 高度?

#include <stdlib.h>
#include <stdio.h>
void max_per_row( double *result, 
                      double matrix[][3], 
                      const int xmax, 
                      const int ymax)
{
int x=0, y=0;

 for(y=0; y < ymax; y++)
    result[y]=y;
for(y=0; y < ymax; y++)
{
    for(x=0; x < xmax; x++)
    {
        if ( matrix[y][x] > result[y] )
            result[y]=matrix[y][x];
    }
}
}

int main(int argc, char **argv)
{
double test1[3][3]={ {-10, -20, 0},
                     {-13, 0,  13},
                     {-99, 99.99, 100.01}};
double result[10]={0};
int y=0;
max_per_row(result, test1, 3, 3 );
for(y=0; y < 3 ; y++)
    printf("max row %d = %f\n", y, result[y]);
return 0;
}

【问题讨论】:

  • 您在哪一部分遇到了问题?
  • 使用&lt;stdlib.h&gt; 中声明的rand() 函数(和srand())。您可能还需要在&lt;time.h&gt; 中声明的time() 函数。玩得开心。
  • 随机大小? (即随机的nm 值)还是用随机数据归档?
  • @Mike 刚刚填充了随机数。
  • @TJD 我想输入矩阵的行数和列数,并用随机数填充矩阵。

标签: c matrix row


【解决方案1】:
int main()
{
    int random[3][3];
    int i, o;

    srand(time(NULL));
    for(o = 0; o<3; o++)
        for(i = 0; i<3; i++)
            random[o][i] = rand();
    return 0;
}

这样就可以了。如果您想要特定的数据子集,可以在 rand() 的输出上使用 % 运算符,例如:

rand() % 10; // generates a random number 0-9

【讨论】:

  • @downvoter - 这个答案有问题吗?
猜你喜欢
  • 2016-06-30
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2019-10-14
  • 2020-04-20
  • 1970-01-01
相关资源
最近更新 更多