Programming Language/C,C++

C++] 명품 C++ 프로그래밍 4장 실습문제

TwinParadox 2017. 10. 26. 21:09
728x90

개인적으로 C++을 공부할 때 작성해놓았던 코드들을 찾았다.

혼자 책을 사서 독학하던 시절에, 그리고 학부생 시절에 복습하면서 했던 문제들이라서

어떤 문제들은 깔끔히 잘 정리되어 있고, 어떤 문제들은 허접한 버그가 있을 수도 있다.

확인은 해뒀지만, 확인하지 못하거나 고려해야 할 버그, 오탈자 등은 댓글을 남겨주시라. 

그간 공부한 것들을 정리하는 블로그이기 때문에 올려놓는다.


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


#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 << '\n'; }
};
int main()
{
	Color screenColor(255, 0, 0);
	Color *p;
	p = &screenColor; // (1)
	p->show(); // (2)

	Color colors[3]; // (3)
	p = colors; // (4)

	// (5)
	p->setColor(255, 0, 0);
	(p+1)->setColor(0, 255, 0);
	(p+2)->setColor(0, 0, 255);

	// (6)
	for (int i = 0; i < 3; i++)
		(p + i)->show();
}




실습문제 2. 다음과 같은 Sample 클래스가 있다. 다음 main() 함수가 실행되도록 Sample 클래스를 완성하라.


#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 < size; i++)
		cin >> p[i];
}
void Sample::write()
{
	for (int i = 0; i < size; i++)
		cout << p[i] << " ";
	cout << endl;
}
int Sample::big()
{
	int max = p[0];
	for (int i = 1; i < size; i++)
		if (p[i] > max)
			max = p[i];
	return max;
}
Sample::~Sample()
{
	delete[] p;
}
int main()
{
	Sample s(10);
	s.read();
	s.write();
	cout << "가장 큰 수는 " << s.big() << endl;
}




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


#include <iostream>
#include <algorithm>
#include <time.h>
#include <string>
using namespace std;
int main()
{
	srand((unsigned)time(NULL));
	cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)\n";
	while (1)
	{
		cout << ">>";
		string s;
		getline(cin, s, '\n');
		if (s == "exit")
			break;
		else
		{
			char randchar = (char)(65 + rand() % 26);
			string randstr;
			randstr = randchar;
			int randidx = rand() % s.length();
			s.replace(randidx, 1, randstr);
			cout << s << endl;
		}
	}
}




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


#include <iostream>
#include <string>
using namespace std;
int main(void)
{
	cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)\n";
	while (1)
	{
		string s;
		int size;
		cout << ">>";
		getline(cin, s, '\n');

		if (s == "exit")
			break;
		else
		{
			size = s.length();
			for (int i = size - 1; i >= 0; i--)
				cout << s[i];
			cout << endl;
		}
	}
}





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


#include <iostream>
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 radius*radius*3.141592;
}
int main()
{
	Circle list[3];
	int cnt = 0;
	for (int i = 0, r; i < 3; i++)
	{
		cout << "원 " << i + 1 << "의 반지름 >> ";
		cin >> r;
		list[i].setRadius(r);
		if (list[i].getArea() > 100)
			cnt++;
	}
	cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다.\n";
}




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


#include <iostream>
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 radius*radius*3.141592;
}
int main()
{
	Circle *list = nullptr;
	int n, cnt = 0;
	
	cout << "원의 개수 >>";
	cin >> n;
	list = new Circle[n];

	for (int i = 0, r; i < n; i++)
	{
		cout << "원 " << i + 1 << "의 반지름 >> ";
		cin >> r;
		list[i].setRadius(r);
		if (list[i].getArea() > 100)
			cnt++;
	}
	cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다.\n";
}




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


#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()
{
	name = tel = "";
}
void Person::set(string name, string tel)
{
	this->name = name;
	this->tel = tel;
}
int main()
{
	Person list[3];

	cout << "이름과 전화 번호를 입력해주세요.\n";
	for (int i = 0; i < 3; i++)
	{
		string name, tel;
		cout << "사람 " << i + 1 << ">> ";
		cin >> name >> tel;
		list[i].set(name, tel);
	}

	cout << "모든 사람의 이름은 ";
	for (int i = 0; i < 3; i++)
		cout << list[i].getName() << " ";
	cout << endl;

	cout << "전화번호 검색합니다. 이름을 입력하세요>>";
	string s;
	cin >> s;
	for (int i = 0; i < 3; i++)
	{
		if (s == list[i].getName())
		{
			cout << "전화번호는 " << list[i].getTel() << endl;
			break;
		}
	}
}




8. 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다. 다음 main()이 작동하도록 Person과 Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.


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




9. 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


#include <iostream>
#include <string>
using namespace std;
class Circle
{
	int radius;
	string name;
public:
	void setCircle(string name, int radius);
	double getArea() { return radius*radius*3.14; }
	string getName() { return name; }
};
void Circle::setCircle(string name, int radius)
{
	this->name = name;
	this->radius = radius;
}
class CircleManager
{
	Circle *p;
	int size;
public:
	CircleManager() { size = 0; }
	CircleManager(int size);
	~CircleManager() { delete[] p; }
	void searchByName();
	void searchByArea();
};
CircleManager::CircleManager(int size)
{
	this->size = size;
	p = new Circle[size];
	for (int i = 0; i < size; i++)
	{
		string name;
		int radius;
		cout << "원 " << i + 1 << "의 이름과 반지름 >> ";
		cin >> name >> radius;
		p[i].setCircle(name, radius);
	}
}
void CircleManager::searchByName()
{
	string s;
	cout << "검색하고자 하는 원의 이름 >> ";
	cin >> s;
	for (int i = 0; i < size; i++)
		if (p[i].getName() == s)
			cout << "도넛의 면적은 " << p[i].getArea() << endl;
}
void CircleManager::searchByArea()
{
	int s;
	cout << "최소 면적을 정수로 입력하세요 >> ";
	cin >> s;
	cout << s << "보다 큰 원을 검색합니다.\n";
	for (int i = 0; i < size; i++)
	{
		if (p[i].getArea() > s)
			cout << p[i].getName() << "의 면적은 " << p[i].getArea();
		if (i != size - 1)
			cout << ",";
		else
			cout << endl;
	}
}
int main()
{
	int size;
	cout << "원의 개수 >> ";
	cin >> size;

	CircleManager m(size);
	m.searchByName();
	m.searchByArea();
}


728x90
728x90