矩阵相乘

编写一个程序实现矩阵的基本运算(加、减、乘法运算)。(矩阵的维数22) 

#include <iostream>
using namespace std;
class pre
{
public:
    pre();
    void set_a();
    void set_b();
    void display();

    friend pre operator+(pre a,pre b);
    friend pre operator*(pre a,pre b);
    friend pre operator-(pre a,pre b);
private:
    int pr[11][11];
};

pre::pre()
{
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            pr[i][j]=0;
        }
}
void pre::set_a()
{
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            cin>>pr[i][j];
        }
}

void pre::set_b()
{
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            cin>>pr[i][j];
        }
}

void pre::display()
{
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<2; j++)
        {
            cout<<pr[i][j]<<" ";
            if(j==1)
                cout<<endl;
        }
    }
    cout<<endl;
}

pre operator+(pre a,pre b)
{
    pre c;
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            c.pr[i][j]=a.pr[i][j]+b.pr[i][j];
        }
    return c;
}

pre operator*(pre a,pre b)
{
    pre c;
    for(int k=0; k<2; k++)
        for(int i=0; i<2; i++)
            for(int j=0; j<2; j++)
            {
                c.pr[k][j]+=a.pr[k][i]*b.pr[i][j];
            }
    return c;
}

pre operator-(pre a,pre b)
{
    pre c;
    for(int i=0; i<2; i++)
        for(int j=0; j<2; j++)
        {
            c.pr[i][j]=a.pr[i][j]-b.pr[i][j];
        }
    return c;
}

int main()
{
    pre a,b,c;

    cout<<"输入a的 2x2 矩阵:"<<endl;
    a.set_a();

    cout<<"输入b的 2x2 矩阵:"<<endl;
    b.set_b();

    cout<<"a的矩阵:"<<endl;
    a.display();
    cout<<"b的矩阵:"<<endl;
    b.display();

    c=a+b;
    cout<<"a+c矩阵结果为: "<<endl;
    c.display();

    c=a-b;
    cout<<"a-c矩阵结果为: "<<endl;
    c.display();

    c=a*b;
    cout<<"a*c矩阵结果为: "<<endl;
    c.display();

    return 0;
}

结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值