C++/문제풀이
[C++] 두 행렬의 곱 구하기(3x3)
year.number
2022. 6. 14. 20:53
실습 9-4번 문제
두 행렬의 곱 구하기(3x3)
void randomNumbers(int inumbers[][3], int rowSize);
void multiplyMatrix(int a[][3], int b[][3], int c[][3], int rowSize);
void printArray(int num[][3], int rowSize);
//
// main.cpp
//
// Created by yeonsu on 2022/06/14.
//
// 난수(0~9)발생 시키기, 숫자의 출현 빈도수 세기(4행 3열)
#include <iostream>
#include <ctime> //rand 함수
#include <iomanip>
using namespace std;
const int ROW = 4;
const int COL = 3;
void randomNumbers(int inumbers[][3], int rowSize);
void multiplyMatrix(int a[][3], int b[][3], int c[][3], int rowSize);
void printArray(int num[][3], int rowSize);
int main(){
int a[ROW][COL];
int b[ROW][COL];
int c[ROW][COL];
// 난수 함수 호출
randomNumbers(a, 3);
randomNumbers(b, 3);
// 곱셈 함수 호출
multiplyMatrix(a, b, c, 3);
cout << "==================\n";
printArray(a, 3);
cout << "==================\n";
cout << " \n";
cout << " * \n";
cout << "==================\n";
printArray(b, 3);
cout << "==================\n";
cout << " \n";
cout << " = \n";
cout << "==================\n";
printArray(c, 3);
return 0;
}
void printArray(int num[][3], int rowSize) { //2차원 배열 출력
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < COL; col++)
cout << setw(5) << num[row][col];
cout << endl;
}
}
void randomNumbers(int inumbers[][3], int rowSize) {
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < COL; col++)
inumbers[row][col] = rand() % 10;
}
}
void multiplyMatrix(int a[][3], int b[][3], int c[][3], int rowSize) {
int mul[3][3];
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < 3; col++) {
c[row][col] = 0;
for (int x = 0; x < 3; x++) {
c[row][col] += a[row][x] * b[x][col];
}
}
}
}
실행 결과
Key Point
void multiplyMatrix(int a[][3], int b[][3], int c[][3], int rowSize) {
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < 3; col++) {
c[row][col] = 0; // 초기화 시켜줌
for (int x = 0; x < 3; x++) {
c[row][col] += a[row][x] * b[x][col];
}
}
}
}