通过将矩阵传递给函数的C ++程序将两个矩阵相乘
矩阵是数字的矩形阵列,以行和列的形式排列。
矩阵的示例如下。
3*4矩阵具有3行4列,如下所示。
8 6 3 5 7 1 9 2 5 1 9 8
通过将矩阵传递给函数来将两个矩阵相乘的程序如下。
示例
#include<iostream>
using namespace std;
void MatrixMultiplication(int a[2][3],int b[3][3]) {
int product[10][10], r1=2, c1=3, r2=3, c2=3, i, j, k;
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
} else {
cout<<"第一个矩阵是:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"第二个矩阵是:"<<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<<"这两个矩阵的乘积为:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
}
}
int main() {
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };
MatrixMultiplication(a,b);
return 0;
}输出结果
第一个矩阵是: 2 4 1 2 3 9 第二个矩阵是: 1 2 3 3 6 1 2 9 7 这两个矩阵的乘积为: 16 37 17 29 103 72
在上述程序中,两个矩阵a和bmain()如下在函数中初始化。
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };使用MatrixMultiplication()a和b的值调用该函数。如下所示。
MatrixMultiplication(a,b);
在该函数中MatrixMultiplication(),如果第一矩阵中的列数不等于第二矩阵中的行数,则无法执行乘法。在这种情况下,将显示错误消息。给出如下。
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
}矩阵a和b都使用嵌套的for循环显示。下面的代码片段对此进行了演示。
cout<<"第一个矩阵是:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"第二个矩阵是:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;此后,将product[][]矩阵初始化为0。然后使用嵌套的for循环来查找2个矩阵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<<"这两个矩阵的乘积为:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}