【发布时间】:2021-04-11 13:54:09
【问题描述】:
我试图将两个矩阵相乘,这两个矩阵是从一个文本文件中读取的,这就是为什么矩阵的值没有被初始化的原因。这是代码:
int main() {
...
else if (multiplication == true){
if (columnsA == rowsB && rowsA == columnsB){
for(int i = 0; i < rowsA; i++){
for(int j = 0; j < columnsB + 1; j++){
for(int k = 0; k < columnsA; k++){
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
}
else{
printf("\nError: The number of columns in Matrix A must be equal to the number of rows in Matrix B for multiplication");
return 1;
}
}
...
return 0;
}
A 是第一个矩阵,B 是第二个矩阵,C 是输出。 rowsA 是矩阵 A 中的行数,B 是矩阵 matrixB 中的列数。
该代码适用于输出矩阵中的第一个数字,但最后一个数字始终是一个非常长的随机数。
例如,输入将是具有以下值的2x2 矩阵:
第 1 行:3 1
第 2 行:5 2
另一个2x2矩阵具有以下值
row 1: 4 1
row 2: 2 6
输出结果为
row 1: 14 9
row 2: 24 -374793898(or some other long, random number)
前三个数字是正确的(我检查过)但最后一个永远不正确。
【问题讨论】:
-
代码似乎正确。在我看来,在将它们相乘之前,您没有正确填充其中一个矩阵(A、B 和/或 C)
-
注意,测试
rowsA == columsB是没用的。矩阵C不一定是正方形
标签: c matrix multidimensional-array matrix-multiplication