算法训练1——矩阵类

【语言】C++

【任务】实现矩阵的基本变换。

【接口】结构体:Matrix

                  成员变量:int n,m       矩阵大小

                               int a[][]     矩阵内容

              重载运算符:+、-、×

              成员函数:void clear()     清空矩阵

【测试】

【运行】 

【代码】

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

const int MAXN = 3;
const int MAXM = 3; //控制矩阵的维数,此处为计算三维矩阵,如不修改维数则会乱码

struct Matrix{
	int n,m;
	int a[MAXN][MAXM];

	void clear()
	{
		n = m = 0;
		memset(a , 0 , sizeof(a));
	}

	Matrix operator +(const Matrix &b) const
	{
		Matrix tmp;
		tmp.n = n;
		tmp.m = m;

		for(int i = 0 ; i < n ; i++)
		{
			for(int j = 0 ; j < m ; j++)
			{
				tmp.a[i][j] = a[i][j] + b.a[i][j];
			}
		}
		return tmp;
	}

	Matrix operator -(const Matrix &b) const
	{
		Matrix tmp;
		tmp.n = n;
		tmp.m = m;

		for(int i = 0 ; i < n ; i++)
		{
			for(int j = 0 ; j < m ; j++)
			{
				tmp.a[i][j] = a[i][j] - b.a[i][j];
			}
		}
		return tmp;
	}

	Matrix operator *(const Matrix &b) const
	{
		Matrix tmp;
		tmp.clear();
		tmp.n = n;
		tmp.m = b.m;

		for(int i = 0 ; i < n ; i++)
		{
			for(int j = 0 ; j < b.m ; j++)
			{
				for(int k = 0 ; k < m ; k++)
				{
					tmp.a[i][j] += a[i][k]*b.a[k][j];
				}
			}
		}
		return tmp;
	}
};

int main()
{
	struct Matrix a;
	struct Matrix b;
	struct Matrix c;

	a.n = 3;
	a.m = 3;
	b.n = 3;
	b.m = 3;
	c.n = 3;
	c.m = 3;

	cout<<"Please input a Matrix:"<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		for(int j = 0 ; j < 3 ; j++)
		{
			scanf("%d",&a.a[i][j]);
		}
	}

	cout<<"Please input the next Matrix:"<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		for(int j = 0 ; j < 3 ; j++)
		{
			scanf("%d",&b.a[i][j]);
		}
	}

	c = a + b;

	cout<<"The result of the addition of two matrices is:"<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[0][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[1][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[2][i]<<" ";
	}
	cout<<endl;

	c.clear();
	c = a - b;

	cout<<"The result of the subtraction of two matrices is:"<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[0][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[1][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[2][i]<<" ";
	}
	cout<<endl;

	c.clear();
	c = a * b;

	cout<<"The result of the multiplication of two matrices is:"<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[0][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[1][i]<<" ";
	}
	cout<<endl;
	for(int i = 0 ; i < 3 ; i++)
	{
		cout<<c.a[2][i]<<" ";
	}

}

猜你喜欢

转载自blog.csdn.net/qq_37105332/article/details/81170452