简体   繁体   English

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

[英]Matrix Multiplication in C - Problem with inputs

I've written a program which carries out matrix multiplication using functions.我编写了一个使用函数执行矩阵乘法的程序。 The function which i presume is wrong is as follows:我认为错误的 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]);
        }
    }
}

It seems you are missing a "+" at multAns[x][y] = matrix1[x][y] * matrix2[x][y];看来您在multAns[x][y] = matrix1[x][y] * matrix2[x][y]; . .

It should rather be:它应该是:

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

In case your last operation result is 0 then this explains why you get a 0 matrix..如果你最后的操作结果是0那么这就解释了为什么你得到一个 0 矩阵..

EDIT:编辑:

The sign is one of the problems.. There is also something wrong with the way you get input from the user.标志是问题之一。您从用户那里获得输入的方式也有问题。

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

There is an error in your call to scanf It should read您对scanf的调用有误 它应该显示为

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

Also take care with hitting the Enter Key after each input.还要注意在每次输入后按Enter键。 To be safe you should catch it.为了安全起见,你应该抓住它。 Use something like使用类似的东西

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

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

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