使用多维数组的 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;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP