矩阵的乘法运算
公式:
#include <iostream>
using namespace std;
int main()
{
**//矩阵的乘法只有在第一个矩阵的列数与第二个矩阵的行数数相等的时候,矩阵的乘法才有意义**。
//第一个矩阵
int matrix_1[10][10], aRow, aCol;
cout << "请输入第一个矩阵的行和列:" << endl;
cin >> aRow >> aCol;
cout << "请输入矩阵的值:" << endl;
for (auto i = 0; i < aRow; i++)
{
for (auto j = 0; j < aCol; j++)
{
cin >> matrix_1[i][j];
}
}
//第二个矩阵的值
int matrix_2[10][10], bRow, bCol;
cout << "请输入第二个举证的行和列:" << endl;
cin >> bRow >> bCol;
cout << "请输入矩阵的值:" << endl;
for (auto i = 0; i < bRow; i++)
{
for (auto j = 0; j < bCol; j++)
{
cin >> matrix_2[i][j];
}
}
//相乘后的矩阵,注意,矩阵的乘法只有在第一个矩阵的列数与第二个矩阵的行数数相等的时候,矩阵的乘法才有意义。
int matrix_3[10][10];
//将矩阵的元素初始化为0
for (auto i = 0; i < aRow; i++)
{
for (auto j = 0; j < bCol; j++)
{
matrix_3[i][j] = 0;
}
}
while (aCol != bRow)
{
cout << "矩阵1的列数不等于矩阵2的行数,矩阵的乘法是没有意义的" << endl;
}
for (auto i = 0; i < aRow; i++)
{
for (auto j = 0; j < bCol; j++)
{
for (auto k = 0; k < bRow; k++)
{
matrix_3[i][j] += matrix_1[i][k] * matrix_2[k][j];
}
}
}
cout << "输出矩阵的值为:" << endl;
for (auto i = 0; i < 2; i++)
{
for (auto j = 0; j < 2; j++)
{
cout << (matrix_3[i][j]) << endl;
}
}
return 0;
}
//matrix_1={2,2,2
2,2,2
2,2,2};
//matrix_2={2,2,2
2,2,2
2,2,2};
//输出matrix_3={12,12,12,
12,12,12,
12,12,12};
```
矩阵乘法要求第一个矩阵的列数和第二个矩阵的行数相等。