在 C++ 中将 3x3 矩阵相乘

The*_*old -1 c++ math matrix visual-studio

我正在开发一个将两个 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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的结果:

25
73
-1717986851
48
129
-858993331
-1867771963
1566576709
1595991863

Output Matrix:
-858993460-858993460-858993460
-1717986851-858993460-858993460
-85899333112
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

再次提前致谢!:D

Mar*_*ťko 5

所以一开始你不需要int i, j;一开始的那几行。如果你没有它们,编译器会正确地告诉你这results[i][j] = product;是在错误的地方。此外,数组的第一个值不是 atA[1]而是 at A[0]。对于矩阵乘法,我建议您阅读此内容。
因此,解决方案应该如下所示:

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] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};

for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++) {
        for (int u = 0; u < 3; u++)
            results[i][j] += matrix1[i][u] * matrix2[u][j];
    }

cout << endl << "Output Matrix: " << endl;

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        cout << results[i][j] << ".";
    }
    cout << endl;
}
Run Code Online (Sandbox Code Playgroud)