【问题标题】:ANSI C - Input of a numeric matrixANSI C - 数字矩阵的输入
【发布时间】:2012-10-29 20:58:12
【问题描述】:

我必须实现一个执行两个矩阵相乘的 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.
}

【问题讨论】:

    标签: c input matrix


    【解决方案1】:

    这在 C 中有点麻烦。但是如果您不希望用户指定矩阵的维度,则需要一个不断增长的缓冲区来放入数字。您可以使用 realloc 来实现这一点。它会是这样的(未经测试):

    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);
    

    它的作用是逐行读取输入,遍历空格或制表符分隔的标记,将每个标记转换为双精度,并将其分配给一维缓冲区,该缓冲区根据需要进行扩展。我每次将其容量乘以 2,以最大限度地减少重新分配内存所花费的时间(这也是 C++ 向量类所做的)。它还跟踪看到的行数和列数,但不进行任何错误检查,因此实际版本需要更多工作。

    要获得结果矩阵的索引 (i,j) 处的值,您必须计算线性索引:val = mat[i*ncol+j]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多