使用多维数组的C++矩阵乘法程序
矩阵是由数字组成的矩形数组,排列成行和列的形式。
矩阵示例如下所示。
一个3*3矩阵有3行3列,如下所示:
8 6 3 7 1 9 5 1 9
一个使用多维数组进行两个矩阵相乘的程序如下所示。
示例
#include<iostream> using namespace std; int main() { int product[10][10], r1=2, c1=3, r2=3, c2=3, i, j, k; int a[2][3] = { {2, 4, 1} , {2, 3, 9} }; int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} }; if (c1 != r2) { cout<<"Column of first matrix should be equal to row of second matrix"; } else { cout<<"The first matrix is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c1; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is:"<<endl; for(i=0; i<r2; ++i) { for(j=0; j<c2; ++j) cout<<b[i][j]<<" "; cout<<endl; } cout<<endl; for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { product[i][j] = 0; } for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { product[i][j]+=a[i][k]*b[k][j]; } cout<<"Product of the two matrices is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) cout<<product[i][j]<<" "; cout<<endl; } } return 0; }
输出
The first matrix is: 2 4 1 2 3 9 The second matrix is: 1 2 3 3 6 1 2 9 7 Product of the two matrices is: 16 37 17 29 103 72
在上面的程序中,两个矩阵a和b的初始化如下所示。
int a[2][3] = { {2, 4, 1} , {2, 3, 9} }; int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };
如果第一个矩阵的列数不等于第二个矩阵的行数,则无法执行乘法。在这种情况下,将打印错误消息。它如下所示。
if (c1 != r2) { cout<<"Column of first matrix should be equal to row of second matrix"; }
两个矩阵a和b都使用嵌套for循环显示。这由以下代码片段演示。
cout<<"The first matrix is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c1; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is:"<<endl; for(i=0; i<r2; ++i) { for(j=0; j<c2; ++j) cout<<b[i][j]<<" "; cout<<endl; } cout<<endl;
在此之后,product[][]矩阵初始化为0。然后使用嵌套for循环来查找两个矩阵a和b的乘积。这在下面的代码片段中进行了演示。
for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { product[i][j] = 0; } for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { product[i][j]+=a[i][k]*b[k][j]; }
获得乘积后,将其打印出来。这如下所示。
cout<<"Product of the two matrices is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) cout<<product[i][j]<<" "; cout<<endl; }
广告