繁体   English   中英

C 中的矩阵乘法 - 输入问题

[英]Matrix Multiplication in C - Problem with inputs

我编写了一个使用函数执行矩阵乘法的程序。 我认为错误的 function 如下:

void obtainMatrixElems(int mtrx[][10], int row_elems, int col_elems){
    printf("Kindly enter matrix elements: \n");

    for(int x = 0; x < row_elems; x++){
        for(int y = 0; y < col_elems; y++){
            printf("Enter element at position %d,%d: \n", x+1, y+1);
            scanf("&d", &mtrx[x][y]);
        }
    }
}

看来您在multAns[x][y] = matrix1[x][y] * matrix2[x][y]; .

它应该是:

// Also note the change variables used for referencing cells ...
multAns[x][y] += matrix1[x][z] * matrix2[z][y];

如果你最后的操作结果是0那么这就解释了为什么你得到一个 0 矩阵..

编辑:

标志是问题之一。您从用户那里获得输入的方式也有问题。

    for(int x = 0; x < row_elems; x++){
        for(int y = 0; y < col_elems; y++){
            printf("Enter element at position %d,%d: \n", x+1, y+1);
            // Note the change of "&" to "%" and the extra sequence
            // "\r\n" which expects the user to press ENTER (i.e.:
            // new line) between input cells
            rc = scanf("%d\r\n", &mtrx[x][y]);
            if (rc != 1) {
                printf("ERROR: scanf did not proceed as expected\r\n");
            }
        }
    }

您对scanf的调用有误 它应该显示为

scanf("%d", &mtrx[x][y]);

还要注意在每次输入后按Enter键。 为了安全起见,你应该抓住它。 使用类似的东西

scanf(" %d", &mtrx[x][x]);

暂无
暂无

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

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