【发布时间】:2016-12-07 12:55:38
【问题描述】:
我正在开发一个将两个 3X3 矩阵相乘的程序。我遇到了一些问题,但我无法弄清楚这些问题。任何帮助将不胜感激:D
#include <iostream>
using namespace std;
int main(){
int matrix1[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int matrix2[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int results[3][3];
int product = 0;
int i;
int j;
for (i = 1; i <= 3; i++){
for (j = 1; j <= 3; j++){
product += matrix1[i][j] * matrix2[j][i];
cout << product << endl;
}
results[i][j] = product;
product = 0;
}
cout << endl << "Output Matrix: " << endl;
for (int i = 1; i < 4; i++){
for (int j = 1; j < 4; j++){
cout << results[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
这是我从中得到的结果:
25
73
-1717986851
48
129
-858993331
-1867771963
1566576709
1595991863
Output Matrix:
-858993460-858993460-858993460
-1717986851-858993460-858993460
-85899333112
Press any key to continue . . .
再次提前感谢! :D
【问题讨论】:
-
如果您从未使用
new创建过这些,为什么还要使用delete[] matrix1;aso? -
results[i][j] = product;应该在内部循环体内。 -
首先,您似乎忘记了数组索引从零变为大小减一。
-
尝试在你最喜欢的IDE中打开“watches”窗口使用调试工具,它对于处理这类问题非常好。如果您感到震惊,请返回 stackoverflow 并创建一个问题来描述问题、期望的行为以及您尝试实现的目标,并提供 MCVE。
-
@TripleEEE 因为 C++ 没有对数组进行边界检查。越界会导致未定义的行为,这可能导致崩溃,但编译器或运行时环境不会捕获。
标签: c++ visual-studio math matrix