티스토리 뷰

Q.1 다음은 색의 3요소인 red, green, blue로 색을 추상화한 Color 클래스를 선언하고 활용하는 코드이다. 빈칸을 채워라. red, green, blue는 0~255의 값만 가진다.

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
#include<iostream>
using namespace std;
class Color {
    int red, green, blue;
public:
    Color() { red = green = blue = 0; }
    Color(int r, int g, int b) { red = r; green = g; blue = b; }
    void setColor(int r, int g, int b) { red = r; green = g; blue = b; }
    void show(){cout << red << ' ' << green << ' ' << blue << endl;}
};
int main() {
    Color screenColor(25500); //빨간색의 screenColor 객체 생성
    Color *p; // Color 타입의 포인터 변수 p 선언
    p = &screenColor; //(1) p가 screenColor의 주소를 가지도록 코드 작성
    p->show();//(2) p와 show()를 이용하여 screenColor 색 출력
    Color colors[3];//(3) Color의 일차원 배열 colors 선언. 원소는 3개
    p = colors;//(4) p가 colors 배열을 가르키도록 코드 작성.
 
    //(5) p와 setColor() 이용하여 colors[0], colors[1], colors[2]가
    //각각 빨강, 초록, 파랑색을 가지도록 코드 작성
    p[0].setColor(25500);
    p[1].setColor(0,255,0);
    p[2].setColor(00255);
    
    //(6) p와 show()를 이용하여 colors 배열의 모든 객체의 색 출력. for 문 이용
    for (int i = 0; i < 3; i++)
        p[i].show();
 
    return 0;
}
cs

 

Q.2 다음과 같은 Sample 클래스가 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
class Sample {
    int *p;
    int size;
public
    Sample(int n) {
        size = n; p = new int[n];
    }
    void read();
    void write();
    int big();
    ~Sample();
};
cs

다음 main() 함수가 실행되도록 Sample 클래스를 완성하라.

1
2
3
4
5
6
7
int main() {
    Sample s(10); // 10개 정수 배열을 가진 Sample 객체 생성
    s.read();
    s.write();
    cout << "가장 큰 수는 " << s.big() << endl;
    return 0;
}
cs

정답 :

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
#include<iostream>
using namespace std;
 
class Sample {
    int *p;
    int size;
public
    Sample(int n) {
        size = n; p = new int[n];
    }
    void read();
    void write();
    int big();
    ~Sample();
};
 
void Sample::read() {
    for (int i = 0; i < 10; i++)
        cin >> p[i];
    cout << endl;
}
 
void Sample::write() {
    for (int i = 0; i < 10; i++)
        cout << p[i] << ' ';
    cout << endl;
}
 
int Sample::big() {
    int max = 0;
    for (int i = 0; i < 10; i++) {
        if (max < p[i]),
            max = p[i];
    }
    return max;
}
 
Sample :: ~Sample() {
}
 
int main() {
    Sample s(10); // 10개 정수 배열을 가진 Sample 객체 생성
    s.read();
    s.write();
    cout << "가장 큰 수는 " << s.big() << endl;
    return 0;
}
cs

 

Q.3 string 클래스를 이용하여 사용자가 입력한 영문 한줄을 입력받고 글자 하나만 랜덤하게 수정하여 출력하는 프로그램을 작성하라.

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
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
 
using namespace std;
 
/*
srand((unsigned)time(0)); //시작할 때 마다 , 다른 발생덤수를 방생시키기 위한 seed 설정
int n = rand(); // 0에서 RAND_MAX(32767) 사이의 랜덤한 정수 발생
*/
 
int main() {
    string s;
    string c;
 
    while (true) {
        cout << "아래에 한줄을 입력하세요. (exit를 입력하면 종료합니다.)" << endl;
        getline(cin, s, '\n');
        
        if (s == "exit")
            break;
 
        srand((unsigned)time(0)); 
        int n = rand() % s.length();
        
        c = rand() % 26 + 97;
        s.replace(n, 1, c);
        
        cout << s << endl << endl;
    }
 
    return 0;
}
cs

 

Q.4 string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 문자열로 입력받고 저꾸로 출력하는 프로그램을 작성하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<string>
 
using namespace std;
 
int main() {
    string s;
 
    while (true) {
        cout << "아래에 한줄을 입력하세요. (exit를 입력하면 종료합니다.)" << endl;
        getline(cin, s, '\n');
        
        if (s == "exit")
            break;
 
        for (int i = s.length()-1; i >=0; i--)
            cout << s[i];
        cout << endl;
    }
    return 0;
}
cs

 

Q.5 다음과 같이 원을 추상화한 Circle 클래스가 있다. Circle 클래스와 main() 함수를  작성하고 3개의 Circle 객체를 가진 배열을 선언하고, 반지름 값을 입력받고 면적이 100보다 큰 원의 개수를 출력하는 프로그램을 완성하라. Circle 클래스도 완성하라.

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
#include<iostream>
#include<string>
 
using namespace std;
 
class Circle {
    int radius;
public :
    void setRadius(int radius);
    double getArea();
};
 
void Circle :: setRadius(int radius) {
    this->radius = radius;
}
double Circle::getArea() {
    return 3.14*radius*radius;
}
 
int main() {
    int r, cnt = 0;
    Circle c[3];
    
    for (int i = 0; i < 3; i++) {
        cout << "원 " << i + 1 << "의 반지름 >> "cin >> r;
        c[i].setRadius(r);
        if (c[i].getArea() > 100)
            cnt++;
    }
    cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다." << endl;
 
    return 0;
}
cs

 

Q.6 실습문제 5의 문제를 수정해보자. 사용자로부터 다음과 같이 원의 개수를 입력받고, 원의 개수만큼 반지름을 입력받는 방식으로 수정하라. 원의 개수에 따라 동적으로 배열을 할당받아야 한다.

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
#include<iostream>
#include<string>
 
using namespace std;
 
class Circle {
    int radius;
public :
    void setRadius(int radius);
    double getArea();
};
 
void Circle :: setRadius(int radius) {
    this->radius = radius;
}
double Circle::getArea() {
    return 3.14*radius*radius;
}
 
int main() {
    int n;
    int r, cnt = 0;
    
    cout << "원의 개수 >> "cin >> n; 
    Circle *pc = new Circle[n];
 
    for (int i = 0; i < n; i++) {
        cout << "원 " << i + 1 << "의 반지름 >> "cin >> r;
        pc[i].setRadius(r);
        if (pc[i].getArea() > 100)
            cnt++;
    }
    cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다." << endl;
 
    delete[] pc;
    return 0;
}
cs

 

Q.7 다음과 같은 Person 클래스가 있다. Person 클래스와 main() 함수를 작성하여, 3개의 Person 객체를 가지는 배열을 선언하고, 다음과 같이 키보드에서 이름과 전화번호를 입력받아 출력하고 검색하는 프로그램을 완성하라.

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
#include<iostream>
#include<string>
 
using namespace std;
 
class Person {
    string name;
    string tel;
public:
    Person();
    string getName() { return name; }
    string getTel() { return tel; }
    void set(string name, string tel);
};
 
Person::Person() {}
void Person :: set(string name, string tel) {
    this->name = name;
    this->tel = tel;
}
 
int main() {
    int i;
    string name, tel;
    Person p[3];
 
    cout << "이름과 전화 번호를 입력해 주세요" << endl;
 
    for (i = 0; i < 3; i++) {
        cout << "사람 " << i + 1 <<">> ";
        cin >> name >> tel;
        p[i].set(name, tel);
    }
 
    cout << "모든 사람의 이름은 ";
    for (i = 0; i < 3; i++)
        cout << p[i].getName() << " ";
    cout << endl;
 
    cout << "전화번호 검색합니다. 이름을 입력하세요 >> "cin >> name;
 
    for (i = 0; i < 3; i++) {
        if (p[i].getName() == name) {
            cout<< "전화번호는 " << p[i].getTel() << endl;
            return 0;
        }
    }
    cout << "찾으시는 이름이 없습니다." << endl;
    return 0;
}
cs

 

Q8. 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person {
    string name;
public :
    Person(string name) { this->name = name; }
    string getName() { return name; }
};
 
class Family {
    Person *p;
    int size;
public:
    Family(string name, int size);
    void show();
    ~Family();
};
cs

다음 main()이 작동하도록 Person과 Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.

1
2
3
4
5
6
7
8
9
10
11
12
int main() {
    Family *simpson = new Family("Simpson"3);
    
    simpson->setName(0,"Mr.Simpson");
    simpson->setName(1"Mrs.Simpson");
    simpson->setName(2"Bart Simpson");
    simpson->show();
    
    delete simpson;
 
    return 0;
}
cs

 

정답 :

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
#include<iostream>
#include<string>
 
using namespace std;
 
class Person {
    string name;
public :
    Person() {}
    Person(string name) { this->name = name; }
    string getName() { return name; }
};
 
class Family {
    Person *p;
    int size;
    string name;
public:
    Family(string name, int size) { 
        p = new Person[size];
        this->size = size;
        this->name = name;
    }
    void show() {
        cout << name <<"가족은 다음과 같이 3명 입니다." << endl;
        for (int i = 0; i < size; i++)
            cout <<p[i].getName() << "\t";
        cout << endl;
    }
    void setName(int index, string name) {
        p[index] = Person(name);
    }
    ~Family() {}
};
 
int main() {
    Family *simpson = new Family("Simpson"3);
    
    simpson->setName(0,"Mr.Simpson");
    simpson->setName(1"Mrs.Simpson");
    simpson->setName(2"Bart Simpson");
    simpson->show();
    
    delete simpson;
 
    return 0;
}
cs

 

Q9. 다음은 이름과 반지름을 속성으로 가지 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Circle {
    int radius;
    string name;
public
    void setCircle(string name, int radius);
    double getArea();
    string getName();
};
 
class CircleManager {
    Circle *p;
    int size;
public:
    CircleManager(int size);
    ~CircleManager();
    void searchByName();
    void searchByArea();
};
cs

 

키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 ㅈ반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CirlceManager 클래스도 완성하라.

 

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
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<string>
 
using namespace std;
 
class Circle {
    int radius;
    string name;
public
    void setCircle(string name, int radius) {
        this->name = name;
        this->radius = radius;
    }
    double getArea() { return 3.14*radius*radius; }
    string getName() { return name; }
};
 
class CircleManager {
    Circle *p; //Circle 배열에 대한 포인터
    int size// 배열의 크기
public:
    CircleManager(int size){//size 크기의 배열 동적 생성. 사용자로부터 입력 완료
        int radius;
        string name;
        this->size = size;
 
        p = new Circle[size];
        for (int i = 0; i < size; i++) {
            cout << "원 " << i + 1 << "의 이름과 반지름 >> ";
            cin >> name >> radius;
            p[i].setCircle(name, radius);
        }
    }
    ~CircleManager() { delete[] p; }
 
    void searchByName() {// 사용자로부터 원의 이름을 입력받아 면적 출력
        string name;
        cout << "검색하고자 하는 원의 이름 >> "cin >> name;
        
        for (int i = 0; i < size; i++) {
            if (name == p[i].getName()) {
                cout << p[i].getName() <<"의 면적은 " << p[i].getArea() << endl;
                break;
            }
        }
    }
 
    void searchByArea() { // 사용자로부터 면적을 입력받아 면적보다 큰 원의 이름 출력
        double area;
 
        cout << "최소 면적을 정수로 입력하세요 >>"cin >> area;
        cout << area << "보다 큰 원을 검색합니다." << endl;
 
        for (int i = 0; i < size; i++) {
            if (area <= p[i].getArea()) {
                cout << p[i].getName() << "의 면적은 " << p[i].getArea() << ", ";
            }
        }
        cout << endl;
    }
};
 
int main() {
    int n, radius;
    string name;
 
    cout << "원의 갯수 >> "cin >> n;
    CircleManager *= new CircleManager(n);
 
    c->searchByName();
    c->searchByArea();
 
    return 0;
}
cs

 

 

Q10. 영문자로 구성된 텍스트에 대해 각 알파벳에 해당하는 문자가 몇 개인지 출력하는 히스토그램 클래스 Histogram을 만들어 보자. 대문자는 모두 소문자로 변환하여 처리한다. Histogram 클래스를 활용하는 사례와 실행 결과는 다음과 같다.

1
2
3
4
5
Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
elvisHisto.put("falling in love with you");
elvisHisto.putc('-');
elvisHisto.put("Elvis Presley");
elvisHisto.print();
cs

 

정답 :

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
#include<iostream>
#include<string>
 
using namespace std;
 
class Histogram {
    string sentence;
public:
    Histogram(string sentence) { this->sentence = sentence;}
    void put(string s) {
        sentence += s;
    }
    void putc(char c) { sentence += c; }
    void print();
};
 
void Histogram::print() {
    int cntOfAlphabets = 0;
    int alphabet[26= { 0 };
    
    cout << sentence << endl << endl;
 
    for (int i = 0; i < sentence.length(); i++) {
        sentence[i] = tolower(sentence[i]);
        if (sentence[i] >= 97 && sentence[i] <= 122) {
            alphabet[sentence[i] - 97]++;
            cntOfAlphabets++;
        }
    }
    cout << "총 알파벳 수 " << cntOfAlphabets << endl << endl;
 
    for (int i = 0; i < 26; i++) {
        cout << (char)(97 + i) << " (" << alphabet[i] << ")\t: ";
        for (int j = 0; j < alphabet[i]; j++)
            cout << "*";
        cout << endl;
    }
}
 
int main() {
    Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
    elvisHisto.put("falling in love with you");
    elvisHisto.putc('-');
    elvisHisto.put("Elvis Presley");
    elvisHisto.print();
 
    return 0;
}
cs

 

Q11. 겜블링 게임을 만들어보자. 두 사람이 게임을 진행하며, 선수의 이름을 초기에 입력 받는다. 선수가 번갈아 자신의 차례에서 <Enter> 키를 치면 랜덤한 3개의 수가 생성되고 모두 동일한 수가 나오면 게임에서 이기게 된다. 숫자의 범위가 너무 크면 3개의 숫자가 일치할 가능성이 낮아 숫자의 범위를 0~2로 제한한다. 랜덤 정수 생성은 문제 3번의 힌트를 참고하라. 선수는 Player 클래스로 작성하고, 2명의 선수는 배열로 구성하라. 그리고 게임은 GamblingGame 클래스로 작성하라.

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
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
 
class Player {
    string name;
public:
    Player() { name = ""; };
    void setName(string name){ this->name = name; }
    string getName() { return name; }
};
 
class GamblingGame {
    Player *p;
    int n;//사람 수
public:
    GamblingGame() {
        string name;
        p = new Player[2];
        cout << "첫번째 선수 입력>>"cin >> name;
        p[0].setName(name);
        cout << "두번째 선수 입력>>"cin >> name;
        p[1].setName(name);
    };
    ~GamblingGame() { delete[] p; }
    void playingGame();
    int makingRandomNumber() { int n = rand()%3return n; };
};
 
void GamblingGame::playingGame() {
    string enter;
    int i, n1, n2, n3;
    for (i = 0; ; i++) {
        cout << p[i%2].getName() << ": <Enter>";
        getline(cin, enter, '\n');
        
        srand((unsigned)time(0));
        n1 = makingRandomNumber(); n2 = makingRandomNumber(); n3 = makingRandomNumber();
        
        cout  << endl << "\t" << n1 << "\t" << n2 << "\t" << n3 << "\t";
 
        if (n1 == n2 && n2== n3) {
            cout << p[i%2].getName() << "님 승리!!" << endl;
                break;
        }
        else cout << "아쉽군요!" << endl;
    }
}
 
int main() {
    GamblingGame game;
    game.playingGame();
 
    return 0;
}
cs

 

 

참고 문헌 : 명품 C++ Programming / 황기태 



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

댓글