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 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告