HENU祖传课堂测试:利用运算符重载实现的同阶矩阵乘法

在测试过程中并未因为代码知识困扰,反而是因为忘记了线性代数里最基本的矩阵乘法该如何进行计算,着实令人汗颜【扶额】

遂痛定思痛,在测试后复习线性代数知识,后仅用不到十分钟便完成课堂测试代码【悲】

应有输入样例:

2 2

1 1 1 1 

2 2 2 2 

输出样例:

4 4 

4 4 

具体代码如下:

#include <iostream>
using namespace std;

class Matrix {
public:
    int x, y;
    int data[10][10]={0};
    Matrix(int a, int b) {
        x = a;
        y = b;
    }
    Matrix operator*(const Matrix& other) {
        Matrix result(this->x, other.y);
        for (int i = 0; i < this->x; i++)
            for (int j = 0; j < other.y; j++)
                for (int k = 0; k < other.y; k++)
                    result.data[i][j] += this->data[i][k] * other.data[k][j];
        return result;
    }
    friend ostream& operator<<(ostream& os, const Matrix& m);
    friend istream& operator>>(istream& is, const Matrix& m);
};
istream& operator>>(istream& is, Matrix& m) {
    for (int i = 0; i < m.x; i++) {
        for (int j = 0; j < m.y; j++)is >> m.data[i][j];
    }
    return is;
}
ostream& operator <<(ostream& out, const Matrix& M1) {
    for (int i = 0; i < M1.x; i++) {
        for (int j = 0; j < M1.y; j++) {
            out << M1.data[i][j] << " ";
        }
        out << endl;
    }
    return out;
}
int main() {
    int x, y;
    cin >> x >> y;
    Matrix m1(x, y), m2(x, y);
    cin >> m1;
    cin >> m2;
    // 初始化m1和m2的数据...
    cout << "那么矩阵m1*m2是!!!" << endl;
    cout << (m1 * m2);
    return 0;
}

希望各位同学在打码做题的同时也不要忽视了基础的数学知识,否则便会马失前蹄,一朝倾覆【逃】

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值