cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++矩阵乘法
C++矩阵乘法
作者:--    发布时间:2019-11-20

我们可以在2个矩阵上执行加,减,乘和除运算。 从用户输入一行数字和列号,组成第一个矩阵元素和第二个矩阵元素。 然后,对用户输入的矩阵执行乘法。

在矩阵乘法第一矩阵中,一个行元素乘以第二矩阵所有列元素。

让我们通过下面的图来理解3 * 33 * 3矩阵的矩阵乘法:

下面来看看看c++中的矩阵乘法程序。

#include <iostream>  
using namespace std;  
int main()  
{  
    int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    
    cout<<"enter the number of row=";    
    cin>>r;    
    cout<<"enter the number of column=";    
    cin>>c;    
    cout<<"enter the first matrix element=\n";    
    for(i=0;i<r;i++)    
    {    
        for(j=0;j<c;j++)    
        {    
            cin>>a[i][j];  
        }    
    }    
    cout<<"enter the second matrix element=\n";    
    for(i=0;i<r;i++)    
    {    
        for(j=0;j<c;j++)    
        {    
            cin>>b[i][j];    
        }    
    }    
    cout<<"multiply of the matrix=\n";    
    for(i=0;i<r;i++)    
    {    
        for(j=0;j<c;j++)    
        {    
            mul[i][j]=0;    
            for(k=0;k<c;k++)    
            {    
                mul[i][j]+=a[i][k]*b[k][j];    
            }    
        }    
    }    
    //for printing result    
    for(i=0;i<r;i++)    
    {    
        for(j=0;j<c;j++)    
        {    
            cout<<mul[i][j]<<" ";    
        }    
        cout<<"\n";    
    }    
    return 0;  
}

执行上面代码得到以下结果 -

enter the number of row=3  
enter the number of column=3  
enter the first matrix element= 
1 2 3
1 2 3  
1 2 3       
enter the second matrix element= 
1 1 1  
2 1 2   
3 2 1    
 multiply of the matrix=  
14 9 8      
14 9 8  
14 9 8

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册