【问题标题】:matrix multiplication using arrays gives me wrong answer [closed]使用数组的矩阵乘法给了我错误的答案[关闭]
【发布时间】:2019-08-12 21:20:17
【问题描述】:

我正在尝试将 3x4 和 4x2 矩阵相乘并将 3x2 矩阵输出到屏幕。出于某种原因,我弄错了最后一行,但前两行是正确的。

我已经尝试改变我的条件

    int result[6];
    int rows=3;
    int columns = 2;
    int mvalue=4;

但还是得到了错误的答案。

mvalue 应该是矩阵大小的中间值,在这种情况下为 4 (3x4 × 4x2)。

void multiMatrix(int matrix1[], int matrix2[], int result[], int rows, int columns, int mvalue){

    for(int i=0; i<rows; i++){
        for(int j=0; j<columns; j++){
            result[i*columns+j]=0;
            for(int w=0; w<mvalue; w++){
            result[i*columns+j]= result[i*columns+j]+matrix1[i*columns+w]*matrix2[w*columns+j];
            }
        }
    }


}

#include <iostream>

int main(){

    int matrix1[]={1,2,3,4,
                    1,2,3,4,
                    5,4,5,3};
    int matrix2[]={1,2,
                   3,4,
                   1,2,
                   3,4};

    int result[6];

    int rows=3;
    int columns = 2;
    int mvalue=4;

    multiMatrix(matrix1, matrix2, result, rows, columns, mvalue);
     for(int i=0; i<rows; i++){
        for(int j=0; j<columns; j++){

          std::cout<<result[i*rows+j]<<" ";

        }
        std::cout << std::endl;

}
}

输出应该是:

22 32
22 32
31 48

我得到的实际输出是:

22 32
22 32
1  2

【问题讨论】:

  • 调试器说什么?
  • 听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programsDebugging Guide
  • 您是否尝试过减少输入数据以找到一个较小的错误示例?

标签: c++ arrays matrix matrix-multiplication


【解决方案1】:

计算线应该是这样的:

result[i*columns+j] += matrix1[i*mvalue+w]*matrix2[w*columns+j];

另外,当你打印出值时,你应该打印出来

cout<<result[i*columns+j]<<" ";

而不是

cout<<result[i*rows+j]<<" "; // i * rows is squaring itself

【讨论】:

    【解决方案2】:

    您可以通过 something * columns + something

    同时索引 matrix1matrix2

    这是不对的,因为matrix1 和matrix2 有不同的形状。在一种情况下,乘法应该是 4,在另一种情况下应该是 2。

    我会让你从那里调试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多