求矩阵的乘法

MZJCDD 2008-04-21 10:46:39
#include<iostream.h>
#include<iomanip.h>
int a[3][4]={{4,1,2,5},
{5,2,1,3},
{2,4,5,7}};
int b[4][5]={{5,4,3,2,1},
{2,3,4,5,6},
{1,2,4,5,7},
{1,5,5,5,5}};
int c[3][5];
void main()
{ int c[3][5];
int i,j;
for( i=0;i<3;i++)
{ for( j=0;j<4;j++)
cout<<setw(3)<<a[i][j];
cout<<endl;
}
cout<<endl<<endl;
for( i=0;i<4;i++)
{ for( j=0;j<5;j++)
cout<<setw(3)<<b[i][j];
cout<<endl;
}
for( i=0;i<3;i++)
for( j=0;j<5;j++)
for(int k=0;k<4;k++)
c[i][j]+=a[i][k]*b[k][j];
for( i=0;i<3;i++)
{for(int j=0;j<5;j++)
cout<<setw(5)<<c[i][j];
cout<<endl;
}
}
怎么我的结果不对啊 !请帮忙指点
...全文
194 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
fallening 2008-04-21
  • 打赏
  • 举报
回复

template < class T > class Matrix
{
private:
int Row;
int Column;
T **Data;
public:
......
Matrix & operator* (const Matrix & M);
Matrix & operator* (const T M);
};

...

template < class T > Matrix < T > &Matrix < T >::operator* (const Matrix & M)
{
if (Column != M.Row)
{
exit (EXIT_FAILURE);
}

Matrix < T > Result (Row, M.Column);

for (int i = 0; i < Row; ++i)
{
for (int j = 0; j < M.Column; ++j)
{
for (int k = 0; k < Column; ++k)
{
Result.Data[i][j] += Data[i][k] * M.Data[k][j];
}
}
}
if (Row != Column)
{

for (int i = 0; i < Row; ++i)
{
delete[]Data[i];
}
delete[]Data;
}

Column = Result.Column;
Data = new T *[Row];
for (int i = 0; i < Row; ++i)
{
Data[i] = new T[Column];
for (int j = 0; j < Column; ++j)
{
Data[i][j] = Result[i][j];
}
}
return *this;
}

template < class T > Matrix < T > &Matrix < T >::operator* (const T M)
{
for (int i = 0; i < Row; ++i)
{
for (int j = 0; j < Column; ++j)
{
Data[i][j] *= M;
}
}

return *this;
}


ryfdizuo 2008-04-21
  • 打赏
  • 举报
回复
  4  1  2  5
5 2 1 3
2 4 5 7


5 4 3 2 1
2 3 4 5 6
1 2 4 5 7
1 5 5 5 5
29 48 49 48 49
33 43 42 40 39
30 65 77 84 96
请按任意键继续. . .
ryfdizuo 2008-04-21
  • 打赏
  • 举报
回复
#include <iostream> 
#include <iomanip>
using namespace std;

int a[3][4]=
{
{4,1,2,5},
{5,2,1,3},
{2,4,5,7}};

int b[4][5]={{5,4,3,2,1},
{2,3,4,5,6},
{1,2,4,5,7},
{1,5,5,5,5}};
int c[3][5];
void main()
{ int c[3][5]={0}; //没有初始化;
int i,j;
for( i=0;i <3;i++)
{ for( j=0;j <4;j++)
cout <<setw(3) <<a[i][j];
cout <<endl;
}
cout <<endl <<endl;
for( i=0;i <4;i++)
{ for( j=0;j <5;j++)
cout <<setw(3) <<b[i][j];
cout <<endl;
}
for( i=0;i <3;i++)
for( j=0;j <5;j++)
for(int k=0;k <4;k++)
c[i][j]+=a[i][k]*b[k][j];

for( i=0;i <3;i++)
{for(int j=0;j <5;j++)
cout <<setw(5) <<c[i][j];
cout <<endl;
}
}

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧