我正在尝试用 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/