본문 바로가기
프로그래밍 문제/c++ 문제

c++ 문제 39. 두 행렬의 곱

by 지나팩 2023. 11. 27.

정수 n을 입력 받고, 두 행렬을  n*n 크기로  동적으로 할당하여 각 공간에 요소를 입력받아 저장합니다. 

프로그램 종료 시,할당한 메모리를 해제합니다.

예를 사용자 입력 값이 2인 경우 첫 번째 행렬과 두 번째 행렬 모두 2x2의 행렬이며

따라서 각각 4개의 원소를 입력 받습니다.

 

출력 예)

코드는 아래에~~~~~~~~~~~~~~~~~~~~~~~

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
using namespace std;
 
//행렬 생성
 
int** allocateMatrix(int rows, int cols) {
    int** matrix = new int* [rows];
    for (int i = 0; i < rows; i++) {
        matrix[i] = new int[cols];
    }
    return matrix;
}
//해제
void freeMatrix(int** matrix, int rows) {
    for (int i = 0; i < rows; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
}
 
//입력
void inputMatrix(int** matrix, int rows, int cols) {
    cout << "요소를 입력하세요:\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << "요소 위치: [" << i << "][" << j << "]: ";
            cin >> matrix[i][j];
        }
    }
}
 
//곱
int** multiplyMatrices(int** matrix1, int** matrix2, int size) {
    int** result = allocateMatrix(sizesize);
 
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            result[i][j] = 0;
            for (int k = 0; k < size; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
 
    return result;
}
 
//출력
void printMatrix(int** matrix, int rows, int cols) {
    cout << "행렬:\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}
 
int main() {
    int n;
        
    cout << "행렬 갯수: ";
    cin >> n;
 
    //행렬 생성
    int** matrix1 = allocateMatrix(n, n);
    int** matrix2 = allocateMatrix(n, n);
 
    //요소 입력
    inputMatrix(matrix1, n, n);
    inputMatrix(matrix2, n, n);
 
    //곱
    int** resultMatrix = multiplyMatrices(matrix1, matrix2, n);
 
    //출력
    printMatrix(resultMatrix, n, n);
 
    //해제
    freeMatrix(matrix1, n);
    freeMatrix(matrix2, n);
    freeMatrix(resultMatrix, n);
 
    return 0;
}
 
cs

댓글