-
[C++] 난수 발생 시킨 뒤, 숫자의 출현 빈도수 세기(이차원 배열)C++/문제풀이 2022. 6. 14. 20:10
실습 9-2번
난수(0~9)발생 시키기, 숫자의 출현 빈도수 세기(4행 3열)
const int ROW = 4; const int COL = 3; void randomNumbers(int inumbers[][3], int rowSize); void randomCounts(int inumbers[][3], int rowSize, int counts[]); void graph(int counts[], int size);
// // 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 randomCounts(int inumbers[][3], int rowSize, int counts[]); void graph(int counts[], int size); int main(){ int rowSize = 4; int array [ROW][COL]; srand((unsigned int)(time(0))); cout << "\n\n난수배열" << endl; cout << "=====================" << endl; randomNumbers(array, rowSize); cout << "=====================" << endl << endl; cout << "\n\n빈도배열" << endl; int counts[10] = {0}; //숫자별 빈도 계산 randomCounts(array, rowSize, counts); graph(counts, 10); return 0; } void randomNumbers(int inumbers[][3], int rowSize){ for (int i = 0; i < rowSize; i++){ for (int j = 0; j < 3; j++){ inumbers[i][j] = rand()%10; cout << setw(5) << inumbers[i][j]; } cout << endl; } } void randomCounts(int inumbers[][3], int rowSize, int counts[]){ // 인덱스 출력 for (int i = 0; i<10; i++) cout << setw(5) << i; cout << endl; cout << " "; // 구분자 출력 for (int i = 0; i<10; i++) cout << "----+"; cout << endl; //빈도 계산 for (int i = 0; i< rowSize; i++) for (int j = 0; j < 3; j++) counts[inumbers[i][j]]++; //빈도 출력 for (int i = 0; i < 10; i++) cout << setw(5) << counts[i]; cout << endl << endl; } void graph(int counts[], int size){ for (int i = 0; i < 10; i++){ cout << " " << i << ": "; for (int j = 0; j < counts[i]; j++) cout << '*'; cout << endl; } }
실행 결과
Key Point
1.빈도 계산
void randomCounts(int inumbers[][3], int rowSize, int counts[]){
//빈도 계산
for (int i = 0; i< rowSize; i++)
for (int j = 0; j < 3; j++)
counts[inumbers[i][j]]++;
//빈도 출력
for (int i = 0; i < 10; i++)
cout << setw(5) << counts[i];
cout << endl << endl;
}
'C++ > 문제풀이' 카테고리의 다른 글
[C++] 문자열을 입력받아서 문자열에 포함된 모든 공백 문자를 삭제하는 프로그램 (0) 2022.06.15 [C++] 두 행렬의 곱 구하기(3x3) (0) 2022.06.14 [C++] 2차원 배열에서 최대, 최소값 구하기 (0) 2022.06.14 [C++] ⭐️100개의 임의의 정수(0~0)발생시킨 후 숫자의 출현 빈도수 세기 (0) 2022.06.14 [C++] 배열을 역순으로 만들기 (0) 2022.06.14