C++矩陣乘法

我們可以在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

上一篇: C++交換變數值 下一篇: C++將十進位轉換為二進位