7.04.2017

배열로 숫자의 발생 빈도 계산하기

// C++로 시작하는 객체지향 프로그래밍 p.326 예제 7.3
//배열 이용하여 숫자의 발생 빈도 계산하기, 입력 숫자의 개수는 최대 100개이며 0이 입력되면 입력은 끝내는 것으로 함.
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;

int main(){
int counts[100];
int number; // number read from a file
//Initialize counts
for (int i = 0; i < 100; i++){
counts[i] = 0;
}
cout << "Enter the numbers between 1 and 100 ending with 0: " << endl;

//Read all numbers
cin >> number;
while (number != 0) {
counts[number -1]++;
cin >> number;
}

//Display result
for (int i = 0; i < 100; i++) {
if (counts[i] > 0 )
cout << (i + 1) << "occurs " << counts[i]
<< ((counts[i] == 1) ? " time" : " times") << endl;
}

system("pause");
return 0;
}

댓글 없음:

댓글 쓰기