用户定义的矩阵c

时间:2014-03-06 04:02:06

标签: 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; 

}

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

在您使用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()函数上添加任何边界。有lots of examples on how to do this

答案 2 :(得分:0)

这些行

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

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

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

并设置rand()函数的限制以生成max和min之间的数字。有关详细信息,请参阅rand()