• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

행렬 덧셈 뺄셈 곱셈 코드를 작성해보았습니다. 코드리뷰 부탁부탁드립니다!

22.08.31 13:49 작성 조회수 567

0

#include <iostream>

using namespace std;

//Matrix Size
const int num_row_A = 2;
const int num_col_A = 2;
const int num_row_B = 2;
const int num_col_B = 2;

void printMatrix(int Mat_A[][num_col_A], int Mat_B[][num_col_B])
{
	

	/*print -> */
	cout << "■Matrix A" << endl;
	for (int i = 0; i < num_row_A; ++i)
	{
		for (int j = 0; j < num_col_A; ++j)
			cout << Mat_A[i][j] << "\t";
		cout << endl;
	}

	/*print -> B*/
	cout << "■Matrix B" << endl;
	for (int i = 0; i < num_row_B; ++i)
	{
		for (int j = 0; j < num_col_B; ++j)
			cout << Mat_B[i][j] << '\t';
		cout << endl;
	}

	return;
}

void Add_Matrix(int Mat_A[][num_col_A], int Mat_B[][num_col_B])
{
	cout << "■Add" << endl;

	for (int row = 0; row < num_row_A; ++row)
	{
		for (int col = 0; col < num_col_A; ++col)
			cout << Mat_A[row][col] + Mat_B[row][col] << '\t';
		cout << endl;
	}
	return;
}

void Sub_Matrix(int Mat_A[][num_col_A], int Mat_B[][num_col_B])
{
	cout << "■Sub" << endl;

	for (int row = 0; row < num_row_A; ++row)
	{
		for (int col = 0; col < num_col_A; ++col)
			cout << Mat_A[row][col] - Mat_B[row][col] << '\t';
		cout << endl;
	}
	return;
}

void Mul_Matrix(int Mat_A[][num_col_A], int Mat_B[][num_col_B])
{
	cout << "■Mul" << endl;

	for (int i = 0; i < num_row_A; ++i)// <2
	{
		
		for (int j = 0; j < num_col_B; ++j) // <2
		{
			int result = 0;

			for(int k=0; k<num_row_B;++k)
				result += Mat_A[i][k] * Mat_B[k][j];
			cout << result << '\t';
		}
		cout << endl;

		
	}

			
}

int main()
{
	//Defined Matrix A,B
	int Matrix_A[num_row_A][num_col_A] = { 1,2,3,4 };
	int Matrix_B[num_row_B][num_col_B] = { 5,6,7,8 };
	
	//Print Matrix A,B
	printMatrix(Matrix_A, Matrix_B);

	/*-------------------------구분----------------------*/
	cout << "----------------------------------------------" << endl;
	/*-------------------------구분----------------------*/

	//Add
	Add_Matrix(Matrix_A, Matrix_B);
	//Subtaction
	Sub_Matrix(Matrix_A, Matrix_B);
	//Multiplication
	Mul_Matrix(Matrix_A, Matrix_B);

	return 0;
}

소요시간은 약 2시간 걸렸습니다. 다른건 쉬운데, 행렬곱셈 코드를 작성하는 데에만 시간을 모두 할애했네요..

어떤 점이 좋았는지, 비효율적이고 잘못되었는지 따끔한 지적 정중히 부탁드립니다!

(일부터 행렬 곱,덧,뺄 셈의 예외는 처리하지 않았습니다! )(2x2 3x3과 같이 행과 열이 같은 행렬끼리의 연산으로만 봐주세요!)

답변 1

답변을 작성해보세요.

1

강민철님의 프로필

강민철

2022.09.02

꼼꼼히 읽어보았는데,

크게 잘못된 부분은 없는 듯 합니다 :)

두 시간동안이나 작성하셨다니, 수고 많으셨습니다.