Computer >> Máy Tính >  >> Lập trình >> C ++

Chương trình C ++ để kiểm tra khả năng nhân của hai ma trận

Hai ma trận được cho là có thể nhân được nếu chúng có thể được nhân lên. Điều này chỉ có thể thực hiện được nếu số cột của ma trận thứ nhất bằng số hàng của ma trận thứ hai. Ví dụ.

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.

Một chương trình để kiểm tra tính đa dạng của hai ma trận như sau.

Ví dụ

#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;
}

đầu ra

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

Trong chương trình trên, đầu tiên người dùng nhập các kích thước của hai ma trận. Điều này được hiển thị như sau.

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;

Sau đó, số hàng và số cột của ma trận được in ra. Điều này được hiển thị bên dưới.

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;

Nếu số cột trong ma trận1 bằng số hàng trong ma trận2, thì ma trận được in ra là phép nhân. Nếu không, nó được in ra rằng các ma trận không thể nhân được. Điều này được chứng minh bằng đoạn mã sau.

if(column1 == row2)
cout<<"Matrices are multiplicable";
else
cout<<"Matrices are not multiplicable";