#include <iostream>
#include <math.h>
using namespace std;
void MatrixMultiplication(int * pArry1, int *pArry2, int * pDestArry, int len)
{
int row ;
int col;
row= col = (int)sqrt((double)len);
if (row * col != len) //矩阵不为方阵则提示矩阵无效
{
cout << "Matrix Invalidate!" << endl;
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
int sum = 0;
for (int k = 0; k < row; k++)
{
sum += pArry1[row * i + k] * pArry2[row * k + j]; //某行、某列所有对应元素相乘求和即为新矩阵某行某列的元素
}
pDestArry[row * i + j] = sum; //矩阵相乘所得新矩阵
}
}
}
void main()
{
int p1[][3] =
{
1,2,1,
1,1,1,
2,3,1
};
int p2[][3] =
{
1,1,1,
2,2,2,
3,3,3
};
int p[3][3];
/**************/
int *a = p1[0];
int *b = p2[0];
int *c = p[0];
/*************/
//int *a = &p1[0][0];
//int *b = &p2[0][0];
//int *c = &p[0][0];
MatrixMultiplication(a,b,c,9);
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
cout << c[i*3+j] <<" ";
}
cout << endl;
}
}
【面试题】两个n*n的矩阵相乘--采用一位数组表示
最新推荐文章于 2024-08-25 15:29:18 发布