实验12:Problem G: 强悍的矩阵运算来了

时间:2023-03-08 16:16:21
  1. 这个题目主要是乘法运算符的重载,卡了我好久,矩阵的乘法用3个嵌套的for循环进行,要分清楚矩阵的乘法结果是第一个矩阵的行,第二个矩阵的列所组成的矩阵。
  2. 重载+,*运算符时,可以在参数列表中传两个矩阵引用,分别表示前后进行运算的矩阵,或者是只传运算符之后的矩阵引用,前一个矩阵用的是隐含的this指针指向的矩阵。我用的是后者。
Home Web Board ProblemSet Standing Status Statistics

Problem G: 强悍的矩阵运算来了

Problem G: 强悍的矩阵运算来了

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 171  Solved: 98
[Submit][Status][Web Board]

Description

定义一个Matrix类,用于存储一个矩阵。重载其+、*运算符,分别用于计算两个矩阵的和、乘积;重载其<<和>>运算符,用于输出和输入一个矩阵。要求当两个矩阵不能进行加法或乘法运算时,应该输出Error。

Input

输入第1行N>0,表示有N组测试用例,共2N个矩阵。

每组测试用例包括2个矩阵。每个矩阵首先输入行数、列数,之后是该矩阵的所有元素。

Output

每个测试用例产生一组输出。具体格式见样例。注意:当不能进行加法或乘法运算时,应输出Error。

Sample Input

3
2 2
1 1
1 1
2 2
2 2
2 2
1 1
1
1 2
2 2
1 1
1
2 2
2 2
2 2

Sample Output

Case 1:
3 3
3 3

4 4
4 4
Case 2:
Error

2 2
Case 3:
Error

Error

HINT

Append Code

[Submit][Status][Web Board]

#include<iostream>
#define MAX 102
using namespace std;
class Matrix
{
public:
int r,c,error;
int m[MAX][MAX];
Matrix():error() {}
Matrix operator+(const Matrix &M)
{
Matrix tmp;
tmp.r=M.r;
tmp.c=M.c;
/*for(int i=0;i<tmp.r;i++)
for(int j=0;j<tmp.c;j++)
tmp.m[i][j]=0;*/
if(r!=M.r||c!=M.c)
{
tmp.error=;
return tmp;
}
for(int i=; i<r; i++)
for(int j=; j<c; j++)
{
tmp.m[i][j]=m[i][j]+M.m[i][j];
}
return tmp;
}
Matrix operator*(const Matrix &M)
{
Matrix tmp;
tmp.r=r;
tmp.c=M.c;
for(int i=;i<tmp.r;i++)
for(int j=;j<tmp.c;j++)
tmp.m[i][j]=;
if(c!=M.r)
{
tmp.error=;
return tmp;
}
for(int i=; i<r; i++)
{
for(int j=; j<M.c; j++)
{
int sum = ;
for(int k=; k<M.r; k++)
{
sum += m[i][k] * M.m[k][j];
}
tmp.m[i][j] = sum;
}
}
return tmp;
}
friend istream &operator>>(istream &is,Matrix &M);
friend ostream &operator<<(ostream &os,Matrix &M); };
istream &operator>>(istream &is,Matrix &M)
{
is>>M.r>>M.c;
for(int i=; i<M.r; i++)
for(int j=; j<M.c; j++)
{
is>>M.m[i][j];
}
return is;
}
ostream &operator<<(ostream &os,Matrix &M)
{
if(M.error==)
{
os<<"Error"<<endl;
return os;
}
for(int i=; i<M.r; i++)
for(int j=; j<M.c; j++)
{
if(j!=M.c-)
os<<M.m[i][j]<<" ";
else
os<<M.m[i][j]<<endl;
}
///os<<endl;
return os;
}
int main()
{
int cases, i;
cin>>cases;
for (i = ; i < cases; i++)
{
Matrix A, B, C, D;
cin>>A>>B;
C = A + B;
D = A * B;
cout<<"Case "<<i + <<":"<<endl;
cout<<C<<endl;
cout<<D;
}
return ;
}