πŸ’» Dev & CSC++ Programming

C++ Programming Ch.4 Exercise 5 Solution

Problem: string 클래슀λ₯Ό μ΄μš©ν•˜μ—¬ μ‚¬μš©μžκ°€ μž…λ ₯ν•œ 영문 ν•œ 쀄을 μž…λ ₯λ°›κ³  κΈ€μž ν•˜λ‚˜λ§Œ λžœλ€ν•˜κ²Œ μˆ˜μ •ν•˜μ—¬ 좜λ ₯ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜λΌ. Objective & Hints: string 클래슀둜 λ¬Έμžμ—΄ 닀루기 랜덀 μ •μˆ˜λ₯Ό λ°œμƒμ‹œν‚€κΈ° μœ„ν•΄ λ‹€μŒ 두 라인의 μ½”λ“œκ°€ ν•„μš”ν•˜λ©°, 와 헀더 νŒŒμΌμ„ include ν•΄μ•Ό ν•œλ‹€. 1 2 srand((unsinged)time(0)); // μ‹œμž‘ν•  λ•Œλ§ˆλ‹€, λ‹€λ₯Έ 랜덀수λ₯Ό λ°œμƒμ‹œν‚€κΈ° μœ„ν•œ seed μ„€μ • int n = rand(); // 0μ—μ„œ RAND_MAX(32767) μ‚¬μ΄μ˜ λžœλ€ν•œ μ •μˆ˜ λ°œμƒ 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 #include #include #include #include using namespace std; int main() { string sent; int n; cout << "μ•„λž˜ ν•œ 쀄을 μž…λ ₯ν•˜μ„Έμš”.(exitλ₯Ό μž…λ ₯ν•˜λ©΄ μ’…λ£Œν•©λ‹ˆλ‹€)" ; while(true){ srand((unsigned)time(0)); cout << "\n>>"; getline(cin,sent); if(sent == "exit") break; int length = sent.length(); while(true){ n = rand()%length; if(sent[n]!=' ') break; } int a = rand()%25+95; // μž„μ˜μ˜ 문자 ν•˜λ‚˜ 선택 sent[n] = (char)a; cout << sent; } } Explanation: ...

March 4, 2020 Β· 1 min Β· Sobamemil
πŸ’» Dev & CSC++ Programming

C++ Programming Ch.3 Exercise 6 Solution

Problem: 문제 5λ²ˆμ„ μ°Έκ³ ν•˜μ—¬ 짝수 μ •μˆ˜λ§Œ λžœλ€ν•˜κ²Œ λ°œμƒμ‹œν‚€λŠ” EvenRandom 클래슀λ₯Ό μž‘μ„±ν•˜κ³  EvenRandom 클래슀λ₯Ό μ΄μš©ν•˜μ—¬ 10개의 짝수λ₯Ό λžœλ€ν•˜κ²Œ 좜λ ₯ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μ™„μ„±ν•˜λΌ. 0도 짝수둜 μ²˜λ¦¬ν•œλ‹€. 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 #include #include #include using namespace std; class EvenRandom{ public: EvenRandom(); int next(); int nextInRange(int a, int b); }; EvenRandom::EvenRandom(){ srand((unsigned)time(0)); } int EvenRandom::next() { int ran = rand(); if(ran%2 == 0) return ran; else return --ran; } int EvenRandom::nextInRange(int a, int b){ int ran = rand()%(b-a+1) + a; if(ran%2 == 0) return ran; else return --ran; } int main(){ EvenRandom r; cout << "-- 0μ—μ„œ " << RAND_MAX << "κΉŒμ§€μ˜ 랜덀 μ •μˆ˜ 10 개--" << endl; for(int i=0; i<10; i++) { int n = r.next(); // 0μ—μ„œ RAND_MAX(32767) μ‚¬μ΄μ˜ λžœλ€ν•œ μ •μˆ˜ cout << n << ' '; } cout << endl << endl << "-- 2μ—μ„œ " << "10 κΉŒμ§€μ˜ 랜덀 μ •μˆ˜ 10 개 --" << endl; for(int i=0; i<10; i++) { int n = r.nextInRange(2,10); // 2μ—μ„œ 10 μ‚¬μ΄μ˜ λžœλ€ν•œ μ •μˆ˜ cout << n << ' '; } cout << endl; } Explanation: ...

March 3, 2020 Β· 2 min Β· Sobamemil