编写程序,求出两个4x4的矩阵A与B的和及差,并按矩阵形式输出。进一步考虑求出矩阵A与B的乘积(c++)
2个回答
展开全部
#include<stdio.h>
#include<stdlib.h>
int i,j,k,m1,m2,n1,n2;
int a[100][100],b[100][100],c[100][100]={0};
int main()
{ printf("input 01 m1*n1:\n");
scanf("%d %d",&m1,&n1);
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
{scanf("%d",&a[i][j]);}
printf("input 01 m2*n2:\n");
scanf("%d %d",&m2,&n2);
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
{scanf("%d",&b[i][j]);}
for(i=0;i<m1;i++)
for(j=0;j<n2;j++)
{ for(k=0;k<n1;k++)
c[i][j]+=a[i][k]* b[k][j];
}
printf("resurt:\n");
for(i=0;i<m1;i++)
{ for(j=0;j<n2;j++)
printf("%3d",c[i][j]);
printf("\n");
}
system("pause");
return 0;
}
我写的是矩阵乘积,会乘积就肯定会加减了。
#include<stdlib.h>
int i,j,k,m1,m2,n1,n2;
int a[100][100],b[100][100],c[100][100]={0};
int main()
{ printf("input 01 m1*n1:\n");
scanf("%d %d",&m1,&n1);
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
{scanf("%d",&a[i][j]);}
printf("input 01 m2*n2:\n");
scanf("%d %d",&m2,&n2);
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
{scanf("%d",&b[i][j]);}
for(i=0;i<m1;i++)
for(j=0;j<n2;j++)
{ for(k=0;k<n1;k++)
c[i][j]+=a[i][k]* b[k][j];
}
printf("resurt:\n");
for(i=0;i<m1;i++)
{ for(j=0;j<n2;j++)
printf("%3d",c[i][j]);
printf("\n");
}
system("pause");
return 0;
}
我写的是矩阵乘积,会乘积就肯定会加减了。
2018-04-12
展开全部
#include<iostream>
using namespace std;
class Matrix
{
private:
double data[4][4];
public:
Matrix(){}
friend istream &operator>>(istream &is, Matrix &m);
friend ostream &operator<<(ostream &out, const Matrix &m);
Matrix &operator+(const Matrix &m)const;
Matrix &operator-(const Matrix &m)const;
Matrix &operator*(const Matrix &m)const;
};
int main()
{
Matrix a,b;
cin>>a>>b;
cout<<a+b<<a-b<<a*b;
return 0;
}
istream &operator>>(istream &is, Matrix &m)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
is>>m.data[i][j];
}
}
}
ostream &operator<<(ostream &out, const Matrix &m)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
out<<m.data[i][j]<<' ';
}
out<<endl;
}
}
Matrix &Matrix::operator+(const Matrix &m)const
{
Matrix *ans = new Matrix;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
ans->data[i][j] = data[i][j] + m.data[i][j];
}
}
return *ans;
}
Matrix &Matrix::operator-(const Matrix &m)const
{
Matrix *ans = new Matrix;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
ans->data[i][j] = data[i][j] - m.data[i][j];
}
}
return *ans;
}
Matrix &Matrix::operator*(const Matrix &m)const
{
Matrix *ans = new Matrix;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
ans->data[i][j] = 0;
for(int k = 0; k < 4; k++)
{
ans->data[i][j] += (data[i][k]*data[k][j]);
}
}
}
return *ans;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询