πŸ’» Dev & CSC++ Programming

C++ Programming Ch.3 Exercise 7 Solution

Problem: 문제 5λ²ˆμ„ μ°Έκ³ ν•˜μ—¬ μƒμ„±μžλ₯Ό μ΄μš©ν•˜μ—¬ 짝수 ν™€μˆ˜λ₯Ό 선택할 수 μžˆλ„λ‘ SelectableRandom 클래슀λ₯Ό μž‘μ„±ν•˜κ³  짝수 10개, ν™€μˆ˜ 10개λ₯Ό λžœλ€ν•˜κ²Œ λ°œμƒμ‹œν‚€λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜λΌ. Objective & Hints: 클래슀 μž‘μ„±μ—μ„œ 맀개 λ³€μˆ˜λ₯Ό κ°€μ§„ μƒμ„±μžμ˜ ν™œμš© Execution Result: Code: 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 #include #include #include using namespace std; class SelectableRandom{ int num; public: SelectableRandom(int _num); // λ§€κ°œλ³€μˆ˜λ‘œ 짝수 ν˜Ήμ€ ν™€μˆ˜λ₯Ό λ°›λŠ”λ‹€ int next(); int nextInRange(int a, int b); }; SelectableRandom::SelectableRandom(int _num){ num = _num; srand((unsigned)time(0)); } int SelectableRandom::next() { int ran = rand(); if(num%2 == 0){ // 짝수 return if(ran%2 == 0) return ran; else return --ran; } else { if(ran%2 == 0) // ν™€μˆ˜ return return ++ran; else return ran; } } int SelectableRandom::nextInRange(int a, int b){ int ran = rand()%(b-a+1) + a; if(num%2 == 0) { // 짝수 return if(ran%2 == 0) return ran; else return ++ran; } else { // ν™€μˆ˜ return if(ran%2 == 0) return ++ran; else return ran; } } int main() { SelectableRandom r1(0); // 짝수 랜덀 μ •μˆ˜ λ°œμƒ cout << "-- 0μ—μ„œ " << RAND_MAX << "κΉŒμ§€μ˜ 짝수 랜덀 μ •μˆ˜ 10 개--" << endl; for(int i=0; i<10; i++) { int n = r1.next(); cout << n << ' '; } SelectableRandom r2(1); // ν™€μˆ˜ 랜덀 μ •μˆ˜ λ°œμƒ cout << endl << endl << "-- 2μ—μ„œ " << "9 κΉŒμ§€μ˜ 랜덀 ν™€μˆ˜ μ •μˆ˜ 10 개 --" << endl; for(int i=0; i<10; i++) { int n = r2.nextInRange(2,9); cout << n << ' '; } cout << endl; } Explanation: ...

March 3, 2020 Β· 2 min Β· Sobamemil