C++ 中一个乘以两个矩阵的程序
在本教程中,我们将讨论如何编写一个程序来乘以两个矩阵。
为此,我们将得到两个矩阵,我们的任务是打印这两个矩阵的乘积。唯一的条件是第一个矩阵的列数应等于第二个矩阵的行数。
示例
#include <iostream>
using namespace std;
#define N 4
//multiplying the elements of both matrices
void calc_product(int mat1[][N], int mat2[][N], int res[][N]){
int i, j, k;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++){
res[i][j] = 0;
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
int main(){
int i, j;
int res[N][N];
int mat1[N][N] = {{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int mat2[N][N] = {{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
calc_product(mat1, mat2, res);
cout << "Resultant matrix :\n";
for (i = 0; i < N; i++){
for (j = 0; j < N; j++)
cout << res[i][j] << " ";
cout << "\n";
}
return 0;
}输出
Resultant matrix : 10 10 10 10 20 20 20 20 30 30 30 30 40 40 40 40
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP