0

我必须实现一个执行两个矩阵相乘的 C 程序(是的,家庭作业 :),并且我正在尝试设计一个函数来接收来自用户的输入并对其进行验证。

我最初的想法是:让我们只要求用户输入矩阵(用空格分隔的数字,用换行符分隔的行,并且可能在换行符之后单独使用“e”来表示矩阵的结束),这样程序就会自动计算列和行的数量并将它们存储在二维数组中。但是,如果我事先不知道它们的大小,如何为它们动态分配足够的内存?如果可能,我会避免要求用户手动输入每个矩阵的行数和列数。

此外,针对错误和/或缺失数据(例如字母、垃圾、数字少于其他行等)验证输入的最佳方法是什么?我正在考虑对每一行进行strtok,使用空格作为分隔符将它们拆分,并检查每个标记是否是严格的数字。这是确定每行是否仅包含有效数值的最佳方法吗?有没有更干净和理智的方法?

这是我的伪代码:

function getMatrix () {
   while(true) {
   Receive a matrix as input, until the user enters 'e' in a new line by itself;
   Split the matrix in rows delimited by newlines;
   Split the rows in strings delimited by whitespaces;
   For each string {
     If the string is numeric, save it as matrix[rowNumber][colNumber];
     Else print a warning and discard the entire input;
   }
   If each row of the matrix has an equal number of elements {
      return the matrix as an array of integers;
   } else {
      print a warning and let the user re-enter the data.
  }
 }
}

main () {
    matrix1 = getMatrix;
    matrix2 = getMatrix;

    matrix1x2 = multiply the two matrices (this is the easy part :)
    print matrix1x2.
}
4

1 回答 1

1

This is a bit cumbersome in C. But if you don't want the user to specify the dimensions of the matrix, you will need a growing buffer to put the numbers in. You can implement this using realloc. It would go something like this (not tested):

int n = 0, nmax = 100;
size_t len = 0;
int nrow = 0, ncol = 0;
double * mat = malloc(nmax);
char * line = NULL, *tok;
while(getline(&line, &len, stdin) > 0)
{
    nrow++;
    ncol = 0;
    for(tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t"))
    {
        ncol++; n++;
        if(n > nmax) mat = realloc(mat, (nmax *= 2)*sizeof(double));
        mat[n-1] = atof(tok);
    }
}
mat = realloc(mat, nrol*nrow*sizeof(double));
free(line);

What this is doing is to read input linewise, loop over space or tab-separated tokens, converts each to a double, and assigns it to a one-dimensional buffer, which is expanded as needed. I multiply its capacity by two each time, in order to minimize the time spent on reallocating memory (this is what the C++ vector class does too). It also keeps track of the number of rows and columns seen, but does not do any error checking so a practical version would need a bit more work.

To get the value at index (i,j) of the resulting matrix, you have to calculate a linear index: val = mat[i*ncol+j].

于 2012-10-29T21:13:35.303 回答