我尝试了这段代码,但是出了点问题
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++)
suma = 0;
for (l = 0; l < row2; l++)
suma += a[i][l] * bt[l][j];
c[i][j] = suma;
}
printf("\nMultiplication of 2 matrices:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++)
printf("%2d", c[i][j]);
printf("\n");
}
当我调试它时,它在行和列中都打印出随机数(类似于-895473)
最佳答案
缺少括号。
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) { // added brace
suma = 0;
for (l = 0; l < row2; l++) { // added brace
suma += a[i][l] * bt[l][j];
} // added brace
c[i][j] = suma;
} // added brace
}
内在的括号不是必须的,但是如果您始终使用括号,则将来犯此特定错误的可能性较小。
没有花括号,它看起来像这样,正确缩进了:
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++)
suma = 0;
// Note that j = col2, which means that we are accessing
// array elements out of bounds, which is an error.
for (l = 0; l < row2; l++)
suma += a[i][l] * bt[l][j];
c[i][j] = suma;
}
这显然是错误的。减少错误发生的另一种方法是在循环内移动变量:
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
double suma = 0;
for (int l = 0; l < row2; l++) {
suma += a[i][l] * bt[l][j];
}
c[i][j] = suma;
}
}
这样,如果您删除括号,则会出现错误,因为未定义
j
。 (这在C90中不起作用,但这几天是古老的历史。)关于c - 如何用C语言计算矩阵乘法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36756147/