给定两个矩阵A和B,要求你计算它们的乘积矩阵AB。需要注意的是,只有规模匹配的矩阵才可以相乘。即若A有Ra行、Ca列,B有Rb行、Cb列,则只有Ca与Rb相等时,两个矩阵才能相乘。
输入格式:
输入先后给出两个矩阵A和B。对于每个矩阵,首先在一行中给出其行数R和列数C,随后R行,每行给出C个整数,以1个空格分隔,且行首尾没有多余的空格。输入保证两个矩阵的R和C都是正数,并且所有整数的绝对值不超过100。
输出格式:
若输入的两个矩阵的规模是匹配的,则按照输入的格式输出乘积矩阵AB,否则输出Error: Ca != Rb,其中Ca是A的列数,Rb是B的行数。
输入样例1:
2 3
1 2 3
4 5 6
3 4
7 8 9 0
-1 -2 -3 -4
5 6 7 8
输出样例1:
2 4
20 22 24 16
53 58 63 28
输入样例2:
3 2
38 26
43 -5
0 17
3 2
-11 57
99 68
81 72
输出样例2:
Error: 2 != 3
气煞我也!!!
之前不会vector,用二级指针写的
非得让我用vector再写一遍
呜呜呜
(我是直接改的233
(可能会有些奇怪233
二级指针版本:
https://blog.csdn.net/qq_40468936/article/details/105561138
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<vector>
#include<iomanip>
#include<iostream>
#include<cstring>
#include<list>
#include<set>
#include<functional>
#include<stack>
using namespace std;
typedef long long ll;
#define ture true
#define flase false
class Matrix
{
public:
Matrix(int, int);//1.构造函数
~Matrix();//2.析构函数
friend istream& operator>>(istream&is, Matrix&a);//3.重载>>
int getRow(){return row;}//4
int getColum(){return column;}//5
friend Matrix operator*(Matrix&, Matrix&);//6.重载*
//Matrix(const Matrix&);//7.复制构造函数
void display();//8.输出
private:
int row;
int column;
//int** mat;
vector<vector<int> > mat;
};
Matrix::Matrix(int r, int c)//1.构造函数
{
row = r;
column = c;
for(int i=0;i<r+2;i++){
mat.push_back(vector<int>());
}
}
Matrix::~Matrix()//2.析构函数
{
}
istream& operator>>(istream & is, Matrix & a){//3.重载>>
int n;
for(int i=0; i<a.row; i++)
{
for(int j=0; j<a.column; j++)
{
is>>n;
a.mat[i].push_back(n);
}
}
}
Matrix operator*(Matrix&a, Matrix&b){//6.重载*
int i,j,k,x;
if(a.row==1&&a.column==1)
{
Matrix p (b.row,b.column);
for(i=0;i<b.row;i++){
for(j=0;j<b.column;j++){
p.mat[i].push_back(a.mat[0][0]*b.mat[i][j]);
}
}
return p;
}
else
{
Matrix p (a.row,b.column);
for(i=0; i<a.row; i++)
{
for(j=0; j<b.column; j++)
{
x=0;
for(k=0; k<a.column; k++)
{
x+=a.mat[i][k]*b.mat[k][j];
}
p.mat[i].push_back(x);
}
}
return p;
}
}
/*Matrix::Matrix(const Matrix&p){//7.复制构造函数
this->row=p.row;
this->column=p.column;
this->mat=new int* [p.row+2];
int i,j;
for(i=0; i<p.row+2; i++)
{
this->mat[i]=new int [p.column+2];
for(j=0; j<p.column; j++)
{
this->mat[i][j]=p.mat[i][j];
}
}
}*/
void Matrix::display(){//8.输出
cout<< row<<" "<<column<<endl;
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{
if(j==0){
cout<<mat[i][j];
}else{
cout<<" "<<mat[i][j];
}
}
cout<<endl;
}
}
int main()
{
int a,b,i,j;
cin>>a>>b;
Matrix x(a,b);
cin>>x;
cin>>a>>b;
Matrix y(a,b);
cin>>y;
if(x.getColum()==y.getRow()||x.getColum()==1&&x.getRow()==1||y.getRow()==1&&y.getRow()==1) {
Matrix z=x*y;
z.display();
}else{
cout<<"Error: "<<x.getColum()<<" != "<<y.getRow()<<endl;
}
return 0;
}