如果可以将两个矩阵相乘,则可以将它们相乘。仅当第一矩阵的列数等于第二矩阵的行数时才有可能。例如。
Number of rows in Matrix 1 = 3 Number of columns in Matrix 1 = 2 Number of rows in Matrix 2 = 2 Number of columns in Matrix 2 = 5 Matrix 1 and Matrix 2 are multiplicable as the number of columns of Matrix 1 is equal to the number of rows of Matrix 2.
检查两个矩阵的乘积的程序如下。
#include<iostream> using namespace std; int main() { int row1, column1, row2, column2; cout<<"输入第一个矩阵的尺寸:"<< endl; cin>>row1; cin>>column1; cout<<"Enter the dimensions of the second matrix: "<<endl; cin>>row2; cin>>column2; cout<<"First Matrix"<<endl; cout<<"Number of rows: "<<row1<<endl; cout<<"Number of columns: "<<column1<<endl; cout<<"Second Matrix"<<endl; cout<<"Number of rows: "<<row2<<endl; cout<<"Number of columns: "<<column2<<endl; if(column1 == row2) cout<<"Matrices are multiplicable"; else cout<<"Matrices are not multiplicable"; return 0; }
输入第一个矩阵的尺寸: 2 3 Enter the dimensions of the second matrix: 3 3 First Matrix Number of rows: 2 Number of columns: 3 Second Matrix Number of rows: 3 Number of columns: 3 Matrices are multiplicable
在上面的程序中,首先由用户输入两个矩阵的维数。如下所示。
cout<<"输入第一个矩阵的尺寸:"<< endl; cin>>row1; cin>>column1; cout<<"Enter the dimensions of the second matrix: "<<endl; cin>>row2; cin>>column2;
之后,打印矩阵的行数和列数。如下所示。
cout<<"First Matrix"<<endl; cout<<"Number of rows: "<<row1<<endl; cout<<"Number of columns: "<<column1<<endl; cout<<"Second Matrix"<<endl; cout<<"Number of rows: "<<row2<<endl; cout<<"Number of columns: "<<column2<<endl;
如果矩阵1中的列数等于矩阵2中的行数,则打印出矩阵是可乘的。否则,打印出矩阵不可乘。下面的代码片段对此进行了演示。
if(column1 == row2) cout<<"Matrices are multiplicable"; else cout<<"Matrices are not multiplicable";