您的位置:首页 > 编程语言 > C语言/C++

矩阵相乘C++代码

2015-03-07 12:21 309 查看
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<iomanip>
using namespace std;

void multmat(int A[], int B[], int C[], int m, int n, int p)
{
int i, j, k;
for(i = 0; i < m; ++i)
for(j = 0; j < p; ++j)
{
int s = 0;
for(k = 0; k < n; ++k)
s += A[i*n + k]*B[k*p + j];
C[i*p + j] = s;
}
return;
}

int main(void)
{
const int MAX = 1000;
int A[MAX], B[MAX], C[MAX];
int m, n, p;

cout << "input m,n,p: ";
cin >> m >> n >> p;

if(m*n >= MAX || n*p >= MAX || m*p >= MAX)
{
cout << "mem ex." << endl;
return -1;
}

cout << "input matrix A: " << endl;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
cin >> A[i*n + j];

cout << "input matrix B: " << endl;
for(int i = 0; i < n; ++i)
for(int j = 0; j < p; ++j)
cin >> B[i*p + j];

multmat(A, B, C, m, n, p);

cout<< "the matrix C is: "<< endl;
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < p; ++j)
{
cout << setw(3) << C[i*p + j] << ' ';
}
cout << endl;
}

system("pause");
return 0;
}


用一维的数组来表示二维的矩阵,以增加函数的灵活性.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 矩阵相乘