繁体   English   中英

用户定义的矩阵

[英]User defined matrix in c

明天我的C类有一个项目,部分项目是创建用户定义的矩阵。 用户将输入矩阵有多少行和多少列,以及矩阵中最小和最大的数字。 这些数字在用户定义的数字之间是随机的。 输入所有内容后,应该显示矩阵。

它可以编译并运行,但是除了显示一个随机数外不执行任何操作。

这是我到目前为止的内容:

    float GetUserInfo(){ //getting the user to define the size and values of the matrix

int nrows, ncol, min, max;
int matrix[50][50],i, j;

 printf("Please enter the number of rows and columns for the matrix:\n");
 printf("number of rows: ");
 scanf("%d", &nrows);
 printf("number of columns: ");
 scanf("%d", &ncol);

 printf("Now enter the min and max value:\n");
 printf("min value: ");
 scanf("%d", &min);
 printf("max value: ");
 scanf("%d", &max);


for(i=0;i<nrows;i++){
    for(j=0;j<ncol;j++){

    }
}

matrix[i][j]=rand();
printf("The matrix generated is:\n%d \t", matrix[i][j]);

return; 

}

您没有在循环内分配任何值。 移动matrix[i][j]=rand(); 到循环内。

另外,您需要使用嵌套循环来打印矩阵值。

要生成指定范围内的随机数,应使用matrix[i][j] = min + rand() * (max-min) / RAND_MAX;

在使用rand()之前,您需要将其与srand()一起获得随机数,否则您将一遍又一遍地获得相同的数字:

srand((int)time(NULL));

第二..除非您错误地复制了代码,否则将数字放在循环之外

for(i=0;i<nrows;i++){
    for(j=0;j<ncol;j++){
                       //<--| You wanted that matrix population placed in the loop 
    }                  //   |
}                      //   |
                       //   |
matrix[i][j]=rand();   // ---
printf("The matrix generated is:\n%d \t", matrix[i][j]);  // move this line too

还有一点,因为您在这里要求输入数字或行和列:

 printf("number of rows: ");
 scanf("%d", &nrows);
 printf("number of columns: ");
 scanf("%d", &ncol);

但是您将数组大小硬编码为50x50,应该验证输入的nrowsncol是否在数组的范围之内,否则您将开始尝试访问您不拥有的内存。


最后一点,您要求在其中放置最大值和最小值,但您并未在rand()函数上设置任何边界。 有关如何执行此操作的示例很多

这些线

matrix[i][j]=rand();
printf("The matrix generated is:\n%d \t", matrix[i][j]);

在for循环之外,因此您只会显示一个随机值。 将此行放入嵌套的for循环中

matrix[i][j]=rand();

并设置rand()函数的限制以生成介于最大值和最小值之间的数字。 有关详细信息,请参见rand()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM