C++ 矩阵乘法不产生正确的输出

标签 c++ matrix

我正在尝试用 C++ 将两个二维数组相乘,但预期的输出不正确,以下是我正在尝试的逻辑 -

 int A[l][m]; //creates A l*m matrix or a 2d array.      
for(int i=0; i<l; i++)    //This loops on the rows.
{
    for(int j=0; j<m; j++) //This loops on the columns
    {
        A[i][j] = i+j; // Allocating values to A matrix
    }
}

int B[m][n]; //creates B m*n matrix or a 2d array.
for(int i=0; i<m; i++)    //This loops on the rows.
{
    for(int j=0; j<n; j++) //This loops on the columns
    {
        B[i][j] = i+j+1; // Allocating values to B matrix
    }
}

int C[l][n]; //creates C m*n matrix or a 2d array.
for(int i=0; i<l; i++)    //This loops on the rows.
{
    for(int j=0; j<n; j++) //This loops on the columns
    {
        for(int k=0; k<m; k++) //This loops on the columns
        {
            C[i][j] += A[i][k] * B[k][j]; // Allocating values to C matrix
            //product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
        }
    cout << C[i][j] << "  ";
          }
       cout << "\n";
}

如果我给 l=2 , m=2 和 n =2 我得到以下输出 -

-1077414723 3
15 8

这是不正确的,任何人都可以告诉我这里有什么问题。

最佳答案

你必须将 C[i][j] 初始化为 0。

或者您可以从 0 开始求和,然后在之后分配给 C[i][j]:

//...
for(int j=0; j<n; j++) //This loops on the columns
{
   int sum = 0;
   for(int k=0; k<m; k++) //This loops on the columns
   {
      sum += A[i][k] * B[k][j]; // Allocating values to C matrix
      //product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
   }
   C[i][j] = sum;
   cout << C[i][j] << "  ";
}
//...

关于C++ 矩阵乘法不产生正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22466757/

相关文章:

Python CSV 将一列中的数据转置为行

c++ - 使用数组填充对称矩阵

c++ - 使用 mkdir() 创建文件夹后,如何让程序将文件和其他信息保存到新文件夹中

c++ - 在 VSCode 中编译 C++ 给我一个 undefined reference

c++ - 检查文件是否被进程文件句柄锁定

python - 矩阵运算后得到输出

ruby - Ruby Matrix 类的复制/继承(核心/标准库)

c++ - 如何在具有大端架构的机器上测试您的代码?

c++ - 用于 boost 序列化的与顺序无关的输入存档

algorithm - 单应性算法未按预期工作