2023.5.22编程一小时打卡

发布时间 2023-05-22 21:48:33作者: 信2211-8李欣垚

一、问题描述:

线性代数中的矩阵可以表示为一个row*column的二维数组,当row和column均为1时,退化为一个数,当row为1时,为一个行向量,当column为1时,为一个列向量。
建立一个整数矩阵类matrix,其私有数据成员如下:

int row;
int column;
int **mat;

建立该整数矩阵类matrix构造函数;
建立一个 *(乘号)的运算符重载,以便于对两个输入矩阵进行乘法运算;
建立输出函数void display(),对整数矩阵按行进行列对齐输出,格式化输出语句如下:

cout<<setw(10)<<mat[i][j];
//需要#include <iomanip>

主函数里定义三个整数矩阵类对象m1、m2、m3.
###输入格式:
分别输入两个矩阵,分别为整数矩阵类对象m1和m2。
每个矩阵输入如下:
第一行两个整数 r c,分别给出矩阵的行数和列数
接下来输入r行,对应整数矩阵的每一行
每行输入c个整数,对应当前行的c个列元素
###输出格式:
整数矩阵按行进行列对齐(宽度为10)后输出
判断m1和m2是否可以执行矩阵相乘运算。
若可以,执行m3=m1*m2运算之后,调用display函数,对m3进行输出。
若不可以,输出"Invalid Matrix multiplication!"
提示:输入或输出的整数矩阵,保证满足row>=1和column>=1。

二、解题思路:

首先定义一个矩阵类包含行列和定义二维动态数组的三个私有成员数据,并定义一个*运算符重载,最后输入俩个数组并输出俩个相乘的数组结果。

三、代码实现:

 1 #include<iostream>
 2 #include<iomanip>
 3 using namespace std;
 4 class matrix{
 5  private:
 6   int row;     
 7   int column;
 8   int **mat;       
 9  public:
10   matrix(int a=0,int b=0):row(a),column(b){};  
11   void get(int ,int);    
12   void display();        
13   friend bool judge(const matrix &a,const matrix &b);   
14   friend matrix operator*(const matrix &a,const matrix &b); 
15 };
16 void matrix::get(int a,int b){ 
17  int i,j;
18  row=a;                
19  column=b;
20  mat=new int*[a];
21  for(i=0;i<a;i++){     
22   mat[i]=new int[b];
23  }
24  for(i=0;i<row;i++){
25   for(j=0;j<column;j++){
26    cin>>mat[i][j];
27   }
28  }
29 }
30 bool judge(const matrix &a,const matrix &b){
31  if(a.column==b.row||a.column==1&&a.row==1){   
32   return true;                              
33  }else{                                     
34   return false;
35  }
36 }
37 void matrix::display(){
38     int i,j;
39     for(i=0;i<row;i++){
40      for(j=0;j<column;j++){
41       cout<<setw(10)<<mat[i][j];
42   }
43   cout<<endl;         
44  }
45 }
46 matrix operator*(const matrix &a,const matrix &b){
47  matrix c;
48  int i=0,j=0,k=0,l=0,sum=0;
49  if(a.column==1&&a.row==1){ 
50   c.row=b.row;
51   c.column=b.column;
52   c.mat=new int*[b.row];
53  for(i=0;i<b.row;i++){
54   c.mat[i]=new int[b.column];
55  }
56  for(i=0;i<b.row;i++){
57   for(j=0;j<b.column;j++){   
58    c.mat[i][j]=a.mat[0][0]*b.mat[i][j];
59   }
60  }
61  }else{
62  c.row=a.row;    
63  c.column=b.column;
64  c.mat=new int*[a.row];
65  for(i=0;i<a.row;i++){
66   c.mat[i]=new int[b.column];
67  }
68  for(i=0;i<a.row;i++){
69   for(j=0;j<b.column;j++){  
70    for(k=0;k<a.column;k++){
71    sum+=a.mat[i][k]*b.mat[k][j]; 
72    }
73    c.mat[i][j]=sum;
74    sum=0;
75   }
76  }
77  }
78  return c;
79 }
80 int main(){     
81  matrix m1,m2,m3;
82  int a,b;
83  cin>>a>>b;
84  m1.get(a,b);
85  cin>>a>>b;
86  m2.get(a,b);
87  if(judge(m1,m2)){
88   m3=m1*m2;
89   m3.display();
90  }else{
91   cout<<"Invalid Matrix multiplication!"<<endl;
92  }
93  return 0;
94 }