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<<"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;
}
}
}
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;
}输出
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在main()函数中初始化如下。
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };使用a和b的值调用MatrixMultiplication()函数。如下所示。
MatrixMultiplication(a,b);
在MatrixMultiplication()函数中,如果第一个矩阵的列数不等于第二个矩阵的行数,则无法进行乘法运算。在这种情况下,会打印错误消息。如下所示。
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
}使用嵌套for循环显示矩阵a和b。以下代码片段演示了这一点。
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;
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP