【C++实现键盘输入两个矩阵执行加法和乘法运算】

C++实现键盘输入两个矩阵执行加法和乘法运算

 首先声明,初学C++程序有不完善的地方,欢迎大家批评指正。

本程序写了两个简单的函数(矩阵加法MatrixSum()和矩阵乘法MatrixMulti()),然后对其进行调用实现从键盘输入两个矩阵进行运算。
完整代码:

#include
 using namespace std;
//矩阵A+B
void MatrixSum(int** a, int** b, int r1, int c1, int r2, int c2)
{
	if (r1 != r2 || c1 != c2)
	{
		cout << "矩阵A和B的行列不同,不能进行加法运算" << endl;
	}
	else
	{
		//为矩阵C开辟内存
		int** c;
		c = new int* [r1];
		for (int i = 0; i < r1; i++)
		{
			if ((c[i] = new int[c1]) == NULL)
				exit(0);
		}
		cout << "----------------矩阵A+B为------------------" << endl;
		for (int i = 0; i < r1; i++)
		{
			for (int j = 0; j < c1; j++)
			{
				c[i][j] = a[i][j] + b[i][j];
				cout << c[i][j] << " ";
			}
			cout << endl;
		}

	}
}
//矩阵A×B
void MatrixMulti(int** a, int** b, int r1, int c1, int r2, int c2)
{
	int i, j, p;
	if (c1 != r2)
	{
		cout << "矩阵A的列数不等于矩阵B的行数,不能进行乘法运算" << endl;
	}
	else
	{
		//为矩阵C开辟内存
		int** c;
		c = new int* [r1];
		for (i = 0; i < r1; i++)
		{
			if ((c[i] = new int[c2]) == NULL)
				exit(0);
		}
		//初始化矩阵C
		for (i = 0; i < r1; i++)
		{
			for (j = 0; j < c2; j++)
				c[i][j] = 0;
		}

		//执行乘法运算
		cout << "----------------矩阵A×B为------------------" << endl;
		for (i = 0; i < r1; i++)
		{
			for (j = 0; j < c2; j++)
			{
				for (p = 0; p < c1; p++)
				{
					c[i][j] += a[i][p] * b[p][j];
				}

			}

		}
		for (i = 0; i < r1; i++)
		{
			for (j = 0; j < c2; j++)
			{
				cout << c[i][j] << " ";
			}
			cout << endl;
		}

	}
}
int main()
{
	int rows1, cols1, rows2, cols2,n;
	int i, j, ** a, ** b;
	//输入矩阵A的行列数
	cout << "矩阵A行数:";
	cin >> rows1;
	cout << "矩阵A列数:";
	cin >> cols1;
	//输入矩阵B的行列数
	cout << "----------输入矩阵B----------" << endl;
	cout << "矩阵B行数:";
	cin >> rows2;
	cout << "矩阵B列数:";
	cin >> cols2;
	//为矩阵A开辟内存
	a = new int* [rows1];
	for (int i = 0; i < rows1; i++)
	{
		if ((a[i] = new int[cols1]) == NULL)
			exit(0);
	}
	//为矩阵B开辟内存
	b = new int* [rows2];
	for (int i = 0; i < rows2; i++)
	{
		if ((b[i] = new int[cols2]) == NULL)
			exit(0);
	}
	//输入矩阵A
	cout << "请输入矩阵A的数据:" << endl;
	for (i = 0; i < rows1; i++)
	{
		for (j = 0; j < cols1; j++)
		{
			cin >> a[i][j];
		}
	}
	//输入矩阵B
	cout << "请输入矩阵B的数据:" << endl;
	for (i = 0; i < rows2; i++)
	{
		for (j = 0; j < cols2; j++)
		{
			cin >> b[i][j];
		}
	}

	cout << "----------------矩阵A为------------------" << endl;
	for (i = 0; i < rows1; i++)
	{
		for (j = 0; j < cols1; j++)
		{
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
	cout << "----------------矩阵B为------------------" << endl;
	for (i = 0; i < rows2; i++)
	{
		for (j = 0; j < cols2; j++)
		{
			cout << b[i][j] << " ";
		}
		cout << endl;
	}
	cout << "----请选择:1矩阵加法运算,2矩阵乘法运算,3退出-----" << endl;
	cin >> n;
	if (n == 1)
	{
		MatrixSum(a, b, rows1, cols1, rows2, cols2);
	}
	else if (n == 2) 
	{
		MatrixMulti(a, b, rows1, cols1, rows2, cols2);
	}
	else
	{
		exit(0);
	}
}

执行结果演示:
【C++实现键盘输入两个矩阵执行加法和乘法运算】_第1张图片

你可能感兴趣的:(c++)