the multiplication of two matrix in a simple way

The results: 

The matrix a:
   2   5
   7   7
The matrix b:
   7   1
   6   9
The result matrix:
  44  47
  91  70

The codes:

//get the multiplication of two matrix
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int n = 2;
void initialization_matrix(int a[][n]);
void multiplication_matrix(int a[][n], int b[][n], int c[][n]);
void disp(int a[][n]);
int main()
{
    srand((unsigned)time(NULL));
    int a[n][n], b[n][n], c[n][n];
    //give random numbers range from 1 to 10 to matrix a and b
    initialization_matrix(a);
    cout << "The matrix a:"<< endl;
    disp(a);
    initialization_matrix(b);
    cout << "The matrix b:" << endl;
    disp(b);
    //get the result of multiplication between a[][n] and b[][n]
    for(int i = 0; i<n; ++i){
        for(int j = 0; j < n; ++j){
            c[i][j] = 0;
        }
    }
    multiplication_matrix(a, b, c);
    //display the elements in matrix c
    cout << "The result matrix:" << endl;
    disp(c);
}
void initialization_matrix(int a[][n])
{
    for(int i = 0; i<n; ++i){
        for(int j = 0; j < n; ++j){
            a[i][j] = rand()%10 + 1;
        }
    }
}
void disp(int a[][n])
{
    for(int i = 0; i<n; ++i){
        for(int j = 0; j < n; ++j){
           cout<< setw(4)<< a[i][j];
        }
        cout << endl;
    }
}
void multiplication_matrix(int a[][n], int b[][n], int c[][n])
{
    for(int i =0; i<n;++i){
        for(int j =0; j <n; ++j){
              for(int k=0; k<n; ++k){
                    c[i][j] += a[i][k]*b[k][j];
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/120813204
今日推荐