0
点赞
收藏
分享

微信扫一扫

国科大——高性能计算系统习题1

非凡兔 2022-03-11 阅读 63
c++
  1. 矩阵乘法(C++一维数组实现)
#include<iostream>
using namespace std;


class matirx {

private:
	int rows;// 矩阵行数
	int cols;// 矩阵列数
	int* mValue;// 矩阵的值

public: 
	// 标准构造函数格式
	
	matirx() {}
	// 获取输入
	void initMatirx() {
		// 获取矩阵的行列和值
		cout << "请输入行数:";
		cin >> this->rows;
		cout << endl;
		cout << "请输入列数:";
		cin >> this->cols;
		cout << endl;
		this->mValue = new int[rows * cols];
		for (int i = 0; i < rows; i++)
			for (int j = 0; j < cols; j++) {
				cout << "请输入m[" << i + 1 << "][" << j + 1 << "]:";
				cin >> mValue[i * cols + j];
				cout << endl;
			}
	}
	void deleteMatirx() {
		delete[] this->mValue;
	}



	// 打印矩阵
	void printMatirx() {
		for (int i = 0; i < rows; i++){
			for (int j = 0; j < cols; j++) {
				cout << mValue[i * cols+ j]<<"\t";
			}
			cout << endl;	
		}
	}
	// 重载加法运算符进行矩阵相乘
	matirx operator+(const matirx &m2) {
		// 行和列
		if (this->cols != m2.rows) {
			cout << "input error!!!";
			return matirx();// 返回空对象
		}
		
		matirx m3;
		m3.mValue = new int[rows * m2.cols];
		m3.rows = rows;
		m3.cols = m2.cols;
		// 矩阵乘法
		int sum = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < m2.cols; j++) {
				for (int k = 0; k < cols; k++) {
					sum += mValue[i * cols + k] * m2.mValue[j + k * m2.cols];
				}
				m3.mValue[i*m2.cols + j ] = sum;// 离大普
				sum = 0;
			}
			
		}	
		return m3;
	}

	int getRows() {
		return this->rows;
	}
	int getCols() {
		return this->cols;
	}

};



int main()
{
	
	matirx m1,m2,m3;
	m1.initMatirx();
	m2.initMatirx();

	cout << "m1:" << endl;
	m1.printMatirx();
	cout << "m2:" << endl;
	m2.printMatirx();

	m3 = m1 + m2;
	m3.printMatirx();
	

	




}
举报

相关推荐

0 条评论