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

C++ matrix multiplication not producing correct output

本文关键字:输出 不能 c++      更新时间:2023-10-16

我试图在c++中乘以两个2D数组,但预期的输出是不正确的,以下是我的逻辑我正在尝试-

 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我得到以下输出-

3
-107741472315 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] << "  ";
}
//...

你有未定义的行为: int C[l][n];被声明但从未初始化。

通常,memset用于将内存归零,或者只是循环遍历元素并将它们设置为零(使用现代编译器,速度一样快)。

您没有将c[i][j]初始化为0。使用

int c[2][2]= {{0}};

这将初始化数组的第一个元素。但是,如果初始化数组中的某些元素,则未初始化的元素将被设置为0。