1. 문제
5. 짝수 홀수를 선택할 수 있도록 생성자를 가진 SelectableRandom 클래스를 작성하고 각각 짝수 10개, 홀수 10개를 랜덤하게 발생시키는 프로그램을 작성하라.
2. 결과
3. 코드
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
class SelectableRandom {
string s;
public :
SelectableRandom(string s) { this->s =s; srand( (unsigned)time(0) ) ;}
int next();
int nextInRange(int a, int b);
string getstr() { return s; }
};
int SelectableRandom::next() {
int n = rand();
if( s == "홀수" )
while( n % 2 == 0 ) n = rand();
else if( s == "짝수" )
while( n % 2 == 1 ) n = rand();
return n;
}
int SelectableRandom::nextInRange(int a, int b) {
int n;
n = a + ( rand() % (b-a+1) );
if ( s == "홀수" )
while( n % 2 == 0 ) n = a + ( rand() % (b-a+1) );
else if( s == "짝수" )
while( n % 2 == 1 ) n = a + ( rand() % (b-a+1) );
return n;
}
int main() {
SelectableRandom r("짝수");
SelectableRandom rr("홀수");
cout << "-- 0에서 " << RAND_MAX << "까지의 "<< r.getstr() << " 랜덤 정수 10 개--" << endl;
for(int i=0; i<10; i++) {
int n = r.next();
cout << n << ' ';
}
cout << endl << endl << "-- 2에서 " << "9 까지의 랜덤 " << rr.getstr() <<" 정수 10 개 --" << endl;
for(int i=0; i<10; i++) {
int n = rr.nextInRange(2, 9);
cout << n << ' ';
}
cout << endl;
}
4. 설명
홀수, 짝수 둘 중 하나를 매개변수로 가지는 생성자를 만든 후 홀수, 짝수를 입력 받은 후 string변수 s에 저장합니다.
그 후 4번과 유사하게, 저장된 변수 값이 짝수이면 while( n % 2 == 1 )로 짝수가 나올 때까지,
홀수이면 while( n % 2 == 0)으로 홀수가 나올 때까지 반복문이 실행되도록하면 됩니다.
'명품 C++ programming' 카테고리의 다른 글
명품 C++ programming 실습문제 3장 7번 (1) | 2019.04.06 |
---|---|
명품 C++ programming 실습문제 3장 6번 (0) | 2019.04.06 |
명품 C++ programming 실습문제 3장 4번 (0) | 2019.04.06 |
명품 C++ programming 실습문제 3장 3번 (0) | 2019.04.06 |
명품 C++ programming 실습문제 3장 2번 (0) | 2019.04.06 |