如果两个矩阵A和B,符合条件A为一个m*n的矩阵,B为一个n*p的矩阵,则两个矩阵可以相乘,A*B的结果为一个m*p的矩阵C。
C11 = A11*B11+A12*B21+......+A1n*Bn1
.
.
.
C1p = A11*B1p+A12*2p+......+A1n*Bnp
.
.
.
Cnp = Am1*B1p+Am2*B2p+......+Amn*Bnp
#include <iostream>
using namespace std;
int fnMatrixMultriply(const int*,const int*,int*,const int,const int,const int);
int main()
{
int m,n,p;
int i,j;
cout << "请输入矩阵A的维数m*n:" << endl;
cout <<"m=";
cin >> m;
cout <<"n=";
cin >> n;
int* iarrA = new int[m*n];
cout << "请输入矩阵A各元素:" << endl;
for(i = 0;i < m;i++)
{
for(j = 0;j < n;j++)
{
cout << "iarrA" << i << j << "=";
cin >> iarrA[i*n+j];
}
}
cout << "请输入矩阵B的列数p:" << endl;
cout <<"p=";
cin >> p;
int* iarrB = new int[n*p];
cout << "请输入矩阵B各元素:" << endl;
for(i = 0;i < n;i++)
{
for(j = 0;j < p;j++)
{
cout << "iarrB" << i << j << "=";
cin >> iarrB[i*p+j];
}
}
int* iarrC = new int[m*p];
fnMatrixMultriply(iarrA,iarrB,iarrC,m,n,p);
cout << "矩阵C=A*B,C的元素是:" << endl;
for(i = 0;i < m;i++)
{
for(j = 0;j < p;j++)
{
cout << iarrC[i*p+j] << "\t";
}
cout << endl;
}
delete[] iarrA;
delete[] iarrB;
delete[] iarrC;
return true;
}
int fnMatrixMultriply(const int* iarrA,const int* iarrB,int* iarrC,const int m,const int n,const int p)
{
int itemp;
if((m <= 0) || (n <= 0) || (p <= 0))
{
cout << "错误:数组维数m,n,p必须大于0!" << endl;
return false;
}
for(int i = 0;i < m;i++)
{
for(int j = 0;j < p;j++)
{
itemp = 0;
for(int k = 0;k < n;k++)
{
itemp = itemp + iarrA[i*n+k] * iarrB[k*p+j];
}
iarrC[i*p+j] = itemp;
}
}
}