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

更新日期: 19-12-2019

421 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.