Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 두 행렬을 곱하는 프로그램

<시간/>

이 자습서에서는 두 행렬을 곱하는 프로그램에 대해 설명합니다.

이를 위해 두 개의 행렬이 주어지며 우리의 임무는 두 행렬의 곱을 출력하는 것입니다. 유일한 조건은 첫 번째 행렬의 열 수가 두 번째 행렬의 행 개수와 같아야 한다는 것입니다.

예시

#include <iostream>
using namespace std;
#define N 4
//multiplying the elements of both matrices
void calc_product(int mat1[][N], int mat2[][N], int res[][N]){
   int i, j, k;
   for (i = 0; i < N; i++) {
      for (j = 0; j < N; j++){
         res[i][j] = 0;
         for (k = 0; k < N; k++)
            res[i][j] += mat1[i][k] * mat2[k][j];
      }
   }
}
int main(){
   int i, j;
   int res[N][N];
   int mat1[N][N] = {{1, 1, 1, 1},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {4, 4, 4, 4}};
   int mat2[N][N] = {{1, 1, 1, 1},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {4, 4, 4, 4}};
   calc_product(mat1, mat2, res);
   cout << "Resultant matrix :\n";
   for (i = 0; i < N; i++){
      for (j = 0; j < N; j++)
      cout << res[i][j] << " ";
      cout << "\n";
   }
   return 0;
}

출력

Resultant matrix :
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40