Programming Language/C,C++

명품 C++ 프로그래밍 10장 실습문제 - 2

TwinParadox 2018. 7. 1. 09:19
728x90

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

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

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

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

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


지금까지는 실습문제 문제 내용까지 적었지만, 귀찮기도 하고, 굳이 입력할 필요성은 느끼지 않아서 적지 않았다. 차후 게시물을 대대적으로 수정할 때면 추가될지도 모른다.



실습문제 7.

#include <iostream>
using namespace std;
class Circle
{
private:
	int radius;
public:
	Circle() { this->radius = 0; }
	Circle(int radius) { this->radius = radius; }
	int getRadius() { return radius; }
	bool operator > (Circle &ref) { return this->radius > ref.radius; }
	bool operator < (Circle &ref) { return this->radius < ref.radius; }
	bool operator == (Circle &ref) { return this->radius == ref.radius; }
};
template <class T>
T bigger(T a, T b)
{
	if (a > b) return a;
	else return b;
}
int main()
{
	int a = 20, b = 50, c;
	c = bigger(a, b);
	cout << "20과 50 중 큰 값은 " << c << endl;
	Circle waffle(10), pizza(20), y;
	y = bigger(waffle, pizza);
	cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl;
}





실습문제 8.

#include <iostream>
using namespace std;
class Comparable
{
public:
	virtual bool operator > (Circle& op2) = 0;
	virtual bool operator < (Circle& op2) = 0;
	virtual bool operator == (Circle& op2) = 0;
};
class Circle : public Comparable
{
private:
	int radius;
public:
	Circle() { this->radius = 0; }
	Circle(int radius) { this->radius = radius; }
	int getRadius() { return radius; }
	bool operator > (Circle& op2) { return this->radius > op2.radius; }
	bool operator < (Circle& op2) { return this->radius < op2.radius; }
	bool operator == (Circle& op2) { return this->radius == op2.radius; }
};
template <class T>
T bigger(T a, T b)
{
	if (a > b) return a;
	else return b;
}
int main()
{
	int a = 20, b = 50, c;
	c = bigger(a, b);
	cout << "20과 50 중 큰 값은 " << c << endl;
	Circle waffle(10), pizza(20), y;
	y = bigger(waffle, pizza);
	cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl;
}





실습문제 9.

#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
	vector<int> v;
	double aver;
	int num, size = 0;
	while (1)
	{
		cout << "정수를 입력하세요(0을 입력하면 종료)>>";
		cin >> num;
		if (num == 0)
			break;
		size++;
		v.push_back(num);
		aver = 0.0;
		for (int i = 0; i < size; i++)
		{
			cout << v[i] << ' ';
			aver += v[i];
		}
		cout << "\n평균 = " << (double)aver / size << '\n';
	}
}





실습문제 10.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <time.h>
using namespace std;
class Nation
{
private:
	string nation;
	string capital;
public:
	Nation() { nation = "", capital = ""; }
	Nation(string nation, string capital)
	{
		this->nation = nation;
		this->capital = capital;
	}
	string getNation() { return nation; }
	string getCapital() { return capital; }
};
class Game
{
private:
	vector<Nation> v;
	void insert()
	{
		while (1)
		{
			string nation, capital;
			cout << v.size() + 1 << ">>";
			cin >> nation >> capital;
			if (nation == "no" && capital == "no")
				break;
			if (isAlready(nation))
				cout << "already exists !!\n";
			else
				v.push_back(Nation(nation, capital));
		}
	}
	void quiz()
	{
		while (1)
		{
			int idx = rand() % v.size();
			string ans;
			cout << v[idx].getNation() << "의 수도는?";
			cin >> ans;
			if (ans == "exit")
				break;
			if (v[idx].getCapital() == ans)
				cout << "Correct !!\n";
			else
				cout << "NO !!\n";
		}
	}
	bool isAlready(string nation)
	{
		for (int i = 0; i < v.size(); i++)
		{
			if (v[i].getNation() == nation)
				return true;
		}
		return false;
	}
public:
	Game()
	{
		srand((unsigned)time(NULL));
		v.push_back(Nation("미국", "와싱턴"));
		v.push_back(Nation("한국", "서울"));
		v.push_back(Nation("일본", "도쿄"));
		v.push_back(Nation("영국", "런던"));
		v.push_back(Nation("프랑스", "파리"));
		v.push_back(Nation("중국", "베이징"));
	}
	void run()
	{
		int opt;
		cout << "***** 나라의 수도 맞추기 게임을 시작합니다. *****<<\n";
		while (1)
		{
			cout << "정보 입력: 1, 퀴즈: 2, 종료: 3 >>";
			cin >> opt;
			if (opt == 3)
				break;
			if (opt == 1)
			{
				insert();
			}
			else if (opt == 2)
			{
				quiz();
			}
			else
			{
				cout << "무효한 입력\n";
			}
		}
	}
};
int main(void)
{
	Game g;
	g.run();
}





실습문제 11.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <time.h>
using namespace std;
class Book
{
private:
	int year;
	string bookName;
	string authName;
public:
	Book() { year = 0, bookName = authName = ""; }
	Book(int year, string bookName, string authName)
	{
		this->year = year;
		this->bookName = bookName;
		this->authName = authName;
	}
	int getYear() { return year; }
	string getBookName() { return bookName; }
	string getAuthName() { return authName; }
};
class Manage
{
private:
	vector<Book> v;
	void add()
	{
		while (1)
		{
			int year;
			string bookName, authName;
			cout << "년도>>";
			cin >> year;
			if (year == -1)
				break;
			cin.ignore();
			cout << "책이름>>";
			getline(cin, bookName);
			cout << "저자>>";
			getline(cin, authName);
			v.push_back(Book(year, bookName, authName));
		}
	}
	void print(Book& b)
	{
		cout << b.getYear() << "년도, " << b.getBookName() << ", " << b.getAuthName() << endl;
	}
	void searchYear(int year)
	{
		for (int i = 0; i < v.size(); i++)
			if (v[i].getYear() == year)
				print(v[i]);
	}
	void searchBookName(string bookName)
	{
		for (int i = 0; i < v.size(); i++)
			if (v[i].getBookName() == bookName)
				print(v[i]);
	}
	void searchAuthName(string authName)
	{
		for (int i = 0; i < v.size(); i++)
			if (v[i].getAuthName() == authName)
				print(v[i]);
	}
public:
	void run()
	{
		string authName;
		int year;
		cout << "입고할 책을 입력하세요. 년도에 -1을 입력하면 입고를 종료합니다.\n";
		add();
		cout << "총 입고된 책은 " << v.size() << "권입니다.\n";
		cout << "검색하고자 하는 저자 이름을 입력하세요>>";
		cin >> authName;
		searchAuthName(authName);
		cout << "검색하고자 하는 년도를 입력하세요>>";
		cin >> year;
		searchYear(year);
	}
};
int main(void)
{
	Manage m;
	m.run();
}





실습문제 12.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <time.h>
using namespace std;
class Word
{
private:
	string english;
	string korean;
public:
	Word() { english = korean = ""; }
	Word(string eng, string kor) { english = eng, korean = kor; }
	string getEnglish() { return english; }
	string getKorean() { return korean; }
};
class Game
{
private:
	vector<Word> v;
	void insert()
	{
		cout << "영어 단어에 exit를 입력하면 입력 끝" << endl;
		while (1)
		{
			string eng, kor;
			cout << "영어 >>";
			cin >> eng;
			if (eng == "exit")
				break;
			cout << "한글 >>";
			cin >> kor;
			v.push_back(Word(eng, kor));
		}
	}
	void quiz()
	{
		cout << "영어 어휘 테스트를 시작합니다. 1-4 외 다른 입력시 종료." << endl;
		while (1)
		{
			int question = rand() % v.size();
			int tmp, ans;
			vector<pair<int, int> > arr;
			bool arrCheck[4] = { false, };
			arr.push_back(make_pair(question, 0));
			cout << v[question].getEnglish() << "?\n";
			for (; arr.size() < 4;)
			{
				tmp = rand() % v.size();
				bool already = false;
				for (int j = 0; j < arr.size(); j++)
				{
					if (arr[j].first == tmp)
					{
						already = true;
						break;
					}
				}
				if (!already)
					arr.push_back(make_pair(tmp, 0));
			}
			for (int cnt = 0; cnt < 4;)
			{
				tmp = rand() % arr.size();
				if (!arrCheck[tmp])
				{
					cnt++;
					arrCheck[tmp] = true;
					arr[tmp].second = cnt;
					cout << "(" << cnt << ") " << v[arr[tmp].first].getKorean() << " ";
				}
			}
			cout << ":>";
			cin >> ans;
			if (ans == -1)
				break;
			else
			{
				for (int i = 0; i < arr.size(); i++)
				{
					if (arr[i].second == ans)
					{
						if (question == arr[i].first)
							cout << "Excellent !!\n";
						else
							cout << "No. !!\n";
						break;
					}
				}
			}
		}
		cout << "\n";
	}
public:
	Game()
	{
		srand((unsigned)time(NULL));
		v.push_back(Word("human", "인간"));
		v.push_back(Word("society", "사회"));
		v.push_back(Word("bear", "곰"));
		v.push_back(Word("emotion", "감정"));
		v.push_back(Word("picture", "사진"));
		v.push_back(Word("trade", "거래"));
		v.push_back(Word("painting", "그림"));
		v.push_back(Word("paradox", "역설"));
		v.push_back(Word("education", "교육"));
		v.push_back(Word("science", "과학"));
	}
	void run()
	{
		cout << "****** 영어 어휘 테스트를 시작합니다. ******\n";
		int opt;
		while (1)
		{
			cout << "어휘 삽입: 1, 어휘 테스트: 2, 프로그램 종료:그외 키 >> ";
			cin >> opt;
			if (opt == 1)
				insert();
			else if (opt == 2)
				quiz();
			else
				break;
		}
	}
};
int main(void)
{
	Game g;
	g.run();
}



728x90