我正在编写一个程序,它接受两个不同矩阵的元素,然后它将它们相乘,接下来它将它们保存在一个多维数组中。 但它只适用于方阵。 (Visual Studio 2013没有错误。) 如果您帮助我编辑此代码以便将各种矩阵相乘,我将很高兴。
int a, b, c, d;
int Mat1[10][10];
int Mat2[10][10];
int Mat3[10][10];
Back1:
cout << endl << "Enter the number of rows in Matrix 1 : ";
cin >> a;
cout << endl << "Enter the number of columns in Matrix 1 : ";
cin >> b;
cout << endl << "Enter the number of rows in Matrix 2 : ";
cin >> c;
cout << endl << "Enter the number of column in Matrix 2 : ";
cin >> d;
if (b != c) {
cout << endl << "******************************************"
<< "\nThis type of Matrix can't be multiplied . " << endl;
goto Back1;
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
cout << endl << "(MAT 1 ) \n\nEnter the Element of row " << i + 1
<< " column " << j + 1 << " : ";
cin >> Mat1[i][j];
}
}
for (int i = 0; i < c; i++) {
for (int j = 0; j < d; j++) {
cout << endl << "(MAT 2 ) \n\nEnter the Element of row " << i + 1
<< " column " << j + 1 << " : ";
cin >> Mat2[i][j];
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
cout << setw(4) << Mat3[i][j] << setw(4);
}
cout << endl;
}
}
答案 0 :(得分:7)
你的矩阵乘法代码是错误的。而不是:
for (int i = 0; i < a; i++)
{
for (int j = 0; j < d; j++)
{
Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
}
}
你需要:
for (int i = 0; i < a; i++)
{
for (int j = 0; j < d; j++)
{
Mat3[i][j] = 0;
for (int k = 0; k < c; k++)
{
Mat3[i][j] += Mat1[i][k] * Mat2[k][j];
}
}
}