C++ 程序,用于检查两个矩阵的可乘性


两个矩阵如果可以相乘,则称之为可乘的。只有当第一个矩阵的列数等于第二个矩阵的行数时,才有可能相乘。例如。

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<<"Enter the dimensions of the first matrix:"<< 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;
}

产出

Enter the dimensions of the first matrix: 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<<"Enter the dimensions of the first matrix:"<< 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";

更新于: 24-6-2020

276 次浏览

开启你的 职业生涯

完成课程获取认证

开始学习
广告