使用多維陣列的 C++ 程式來新增兩個矩陣


矩陣是以行和列的形式排列的數字矩形陣列。

矩陣的一個示例如下。

一個 4*3 的矩陣具有 4 行和 3 列,如下所示 −

3 5 1
7 1 9
3 9 4
1 6 7

一個使用多維陣列新增兩個矩陣的程式如下。

示例

 動態演示

#include <iostream>
using namespace std;
int main() {
   int r=2, c=4, sum[2][4], i, j;
   int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
   int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
   cout<<"The first matrix is: "<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<a[i][j]<<" ";
      cout<<endl;
   }
   cout<<endl;
   cout<<"The second matrix is: "<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<b[i][j]<<" ";
      cout<<endl;
   }
   cout<<endl;
   for(i=0;i<r;++i)
   for(j=0;j<c;++j)
   sum[i][j]=a[i][j]+b[i][j];
   cout<<"Sum of the two matrices is:"<<endl;
   for(i=0; i<r; ++i) {
      for(j=0; j<c; ++j)
      cout<<sum[i][j]<<" ";
      cout<<endl;
   }
   return 0;
}

輸出

The first matrix is:
1 5 9 4
3 2 8 3

The second matrix is:
6 3 8 2
1 5 2 9

Sum of the two matrices is:
7 8 17 6
4 7 10 12

在上面的程式中,首先定義了兩個矩陣 a 和 b。如下所示。

int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<a[i][j]<<" ";
   cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<b[i][j]<<" ";
   cout<<endl;
}

使用巢狀迴圈新增這兩個矩陣,並將結果儲存在矩陣 sum[] 中。在以下程式碼片段中展示了這一點。

for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];

在獲取到這兩個矩陣的和之後,將其列印到螢幕上。這樣做如下 −

cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
   for(j=0; j<c; ++j)
   cout<<sum[i][j]<<" ";
   cout<<endl;
}

更新於: 2020 年 6 月 24 日

2K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.