«   2025/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

ITGenerations

[c++] p145. n5 짝수 홀수를 선택할 수 있도록 생성자를 가진 SelectableRandom 클래스를 본문

프로그래밍/c++ 명품프로그래밍

[c++] p145. n5 짝수 홀수를 선택할 수 있도록 생성자를 가진 SelectableRandom 클래스를

ITGenerations 2017. 11. 25. 03:10

//-----------------------------------------------------------------------------------------------------------------

// p145. n5. 짝수 홀수를 선택할 수 있도록 생성자를 가진 SelectableRandom 클래스를 작성하고 각각 짝수10개, 홀수10개를

// 랜덤하게 발생시키는 프로그램을 작성하자.

//-----------------------------------------------------------------------------------------------------------------



#include <iostream>

#include <ctime>

#include <random>

#define RAND_MAX 32767

using namespace std;


class SelectableRandom

{

public:

int r;

SelectableRandom()

{

srand((unsigned)time(NULL));

}

int next();

int nextRange(int a, int b);


};



// 0 to MAX_RAND get even numbers

int SelectableRandom::next()

{

int i;

do 

{

i = rand();

} while (i % 2 == 1);

return i;

}


// 2 to 9 get odd numbers

int SelectableRandom::nextRange(int a, int b)

{

int n;

do

{

n = (rand() % (b - a + 1)) + a;

} while (n % 2 == 0);

return n;

}


int main()

{

SelectableRandom s;

cout << "--0에서" << RAND_MAX << "까지의 짝수 랜덤정수 10개--" << endl;

for (int i = 0; i < 10; i++)

{

int r=s.next();

cout << r << ' ';

}

cout << endl;

cout << endl;

cout << endl;

cout << "--2에서 " << "9까지의 랜덤 홀수 정수 10개--" << endl;

for (int i = 0; i < 10; i++)

{

int r = s.nextRange(2, 9);

cout << r << ' ';

}

cout << endl;

return 0;

}