Programming Language/C,C++

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

TwinParadox 2017. 11. 9. 01:42
728x90

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

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

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

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

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


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



실습문제 1.

#include <iostream>
#include <string>
using namespace std;
class Converter
{
protected:
	double ratio;
	virtual double convert(double src) = 0;
	virtual string getSourceString() = 0;
	virtual string getDestString() = 0;
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run()
	{
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};
class WonToDollar : public Converter
{
	double source, dest;
	string sName, dName;
public:
	WonToDollar(double ratio) : Converter(ratio) { sName = "원", dName = "달러"; }
	void setSource(double source) { this->source = source; }
	void setDest(double source) { dest = convert(source); }
	double convert(double src) { return src / ratio; }
	double getDest() { return dest; }
	string getSourceString() { return sName; }
	string getDestString() { return dName; }
};
int main()
{
	WonToDollar wd(1010);
	wd.run();
}



실습문제 2.

#include <iostream>
#include <string>
using namespace std;
class Converter
{
protected:
	double ratio;
	virtual double convert(double src) = 0;
	virtual string getSourceString() = 0;
	virtual string getDestString() = 0;
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run()
	{
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};
class KmToMile : public Converter
{
	double source, dest;
	string sName, dName;
public:
	KmToMile(double ratio) : Converter(ratio) { sName = "Km", dName = "Mile"; }
	void setSource(double source) { this->source = source; }
	void setDest(double source) { dest = convert(source); }
	double convert(double src) { return src / ratio; }
	double getDest() { return dest; }
	string getSourceString() { return sName; }
	string getDestString() { return dName; }
};
int main()
{
	KmToMile toMile(1.609344);
	toMile.run();
}



실습문제 3.

#include <iostream>
#include <string>
using namespace std;
class LoopAdder
{
	string name;
	int x, y, sum;
	void read();
	void write();
protected:
	LoopAdder(string name = "") { this->name = name; }
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0;
public:
	void run();
};
void LoopAdder::read()
{
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}
void LoopAdder::write()
{
	cout << x << "에서 " << y << "까지의 합 = " << sum << "입니다." << endl;
}
void LoopAdder::run()
{
	read();
	sum = calculate();
	write();
}
class ForLoopAdder : public LoopAdder
{
public:
	ForLoopAdder(string name) : LoopAdder(name) {}
	int calculate()
	{
		int sum = 0;
		int x = getX(), y = getY();
		for (int i = x; i <= y; i++)
			sum += i;
		return sum;
	}
};
int main(void)
{
	ForLoopAdder forLoop("For Loop");
	forLoop.run();
}



실습문제 4.

#include <iostream>
#include <string>
using namespace std;
class LoopAdder
{
	string name;
	int x, y, sum;
	void read();
	void write();
protected:
	LoopAdder(string name = "") { this->name = name; }
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0;
public:
	void run();
};
void LoopAdder::read()
{
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}
void LoopAdder::write()
{
	cout << x << "에서 " << y << "까지의 합 = " << sum << "입니다." << endl;
}
void LoopAdder::run()
{
	read();
	sum = calculate();
	write();
}
class WhileLoopAdder : public LoopAdder
{
public:
	WhileLoopAdder(string name) : LoopAdder(name) {}
	int calculate()
	{
		int sum = 0;
		int x = getX(), y = getY();
		while (x <= y)
			sum += x, x++;
		return sum;
	}
};
class DoWhileLoopAdder : public LoopAdder
{
public:
	DoWhileLoopAdder(string name) : LoopAdder(name) {}
	int calculate()
	{
		int sum = 0;
		int x = getX(), y = getY();
		do
		{
			sum += x, x++;
		} while (x <= y);
		return sum;
	}
};
int main(void)
{
	WhileLoopAdder whileLoop("While Loop");
	DoWhileLoopAdder dowhileLoop("Do while Loop");

	whileLoop.run();
	dowhileLoop.run();
}



실습문제 5.

#include <iostream>
#include <string>
using namespace std;
class AbstractGate
{
protected:
	bool x, y;
public:
	void set(bool x, bool y) { this->x = x, this->y = y; }
	virtual bool operation() = 0;
};
class ANDGate : public AbstractGate
{
public:
	bool operation() { return x & y; }
};
class ORGate : public AbstractGate
{
public:
	bool operation() { return x | y; }
};
class XORGate : public AbstractGate
{
public:
	bool operation() { return x^y; }
};
int main(void)
{
	ANDGate and;
	ORGate or ;
	XORGate xor;

	and.set(true, false);
	or .set(true, false);
	xor.set(true, false);
	cout.setf(ios::boolalpha);
	cout << and.operation() << endl;
	cout << or.operation() << endl;
	cout << xor.operation() << endl;
}



실습문제 6.

#include <iostream>
#include <string>
using namespace std;
class AbstractStack
{
public:
	virtual bool push(int n) = 0;
	virtual bool pop(int& n) = 0;
	virtual int size() = 0;
};
class IntStack : public AbstractStack
{
	int* stack;
	int s, top;
public:
	IntStack(int s = 100)
	{
		this->s = s;
		stack = new int[s];
		top = -1;
	}
	bool push(int n)
	{
		if (top >= size() - 1)
		{
			cout << "stack is full.." << endl;
			return false;
		}
		else
		{
			stack[++top] = n;
			return true;
		}
	}
	bool pop(int& n)
	{
		if (top < 0)
		{
			cout << "stack is empty.." << endl;
			return false;
		}
		else
		{
			n = stack[top--];
			return true;
		}
	}
	int size() { return s; }
};
int main(void)
{
	IntStack is(10);
	for (int i = 0; i <= 10; i++)
		is.push(i);
	for (int i = 0; i <= 10; i++)
	{
		int n;
		is.pop(n);
		cout << n << ' ';
	}
}



실습문제 7.

#include <iostream>
#include <string>
using namespace std;
class Shape
{
protected:
	string name;
	int width, height;
public:
	Shape(string n = "", int w = 0, int h = 0) { name = n, width = w, height = h; }
	virtual double getArea() { return 0; }
	string getName() { return name; }
};
class Oval : public Shape
{
public:
	Oval(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height*3.14; }
};
class Rect : public Shape
{
public:
	Rect(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height; }
};
class Triangular : public Shape
{
public:
	Triangular(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height / 2; }
};
int main(void)
{
	Shape* p[3];
	p[0] = new Oval("빈대떡", 10, 20);
	p[1] = new Rect("찰떡", 30, 40);
	p[2] = new Triangular("토스트", 30, 40);
	for (int i = 0; i < 3; i++)
		cout << p[i]->getName() << " 넓이는 " << p[i]->getArea() << endl;
	for (int i = 0; i < 3; i++)
		delete p[i];
}



실습문제 8.

#include <iostream>
#include <string>
using namespace std;
class Shape
{
protected:
	string name;
	int width, height;
public:
	Shape(string n = "", int w = 0, int h = 0) { name = n, width = w, height = h; }
	virtual double getArea() = 0;
	virtual string getName() = 0;
};
class Oval : public Shape
{
public:
	Oval(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height*3.14; }
	string getName() { return name; }
};
class Rect : public Shape
{
public:
	Rect(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height; }
	string getName() { return name; }
};
class Triangular : public Shape
{
public:
	Triangular(string name, int width, int height) : Shape(name, width, height) {}
	double getArea() { return width*height / 2; }
	string getName() { return name; }
};
int main(void)
{
	Shape* p[3];
	p[0] = new Oval("빈대떡", 10, 20);
	p[1] = new Rect("찰떡", 30, 40);
	p[2] = new Triangular("토스트", 30, 40);
	for (int i = 0; i < 3; i++)
		cout << p[i]->getName() << " 넓이는 " << p[i]->getArea() << endl;
	for (int i = 0; i < 3; i++)
		delete p[i];
}



실습문제 9.

#include <iostream>
using namespace std;
class Statistics
{
	int* arr;
	int idx;
	int size;
public:
	Statistics() { arr = new int[5], idx = 0, size = 5; }
	~Statistics() { delete[] arr; }
	bool operator!() { return !(this->idx); }
	Statistics& operator<<(int n)
	{
		if (idx >= size)
		{
			int* tmp = new int[size * 2];
			for (int i = 0; i < size; i++)
				tmp[i] = arr[i];
			delete[] arr;
			arr = tmp, size *= 2;
		}
		arr[idx] = n;
		idx++;
		return *this;
	}
	void operator~()
	{
		for (int i = 0; i < idx; i++)
			cout << arr[i] << ' ';
		cout << endl;
	}
	void operator>>(int& n)
	{
		int sum = 0;
		for (int i = 0; i < idx; i++)
			sum += arr[i];
		n = sum / idx;
	}
};
int main(void)
{
	Statistics stat;
	if (!stat)
		cout << "현재 통계 데이타가 없습니다." << endl;
	int x[5];
	cout << "5 개의 정수를 입력하라>>";
	for (int i = 0; i < 5; i++)
		cin >> x[i];
	for (int i = 0; i < 5; i++)
		stat << x[i];
	stat << 100 << 200;
	~stat;

	int avg;
	stat >> avg;
	cout << "avg=" << avg << endl;
}



실습문제 10.

#include <iostream>
#include <string>
using namespace std;
class Printer
{
	string model, manufacturer;
	int printedCount, availableCount;
protected:
	Printer(string model, string manufacturer, int printedCount, int availableCount)
	{
		this->model = model;
		this->manufacturer = manufacturer;
		this->printedCount = printedCount;
		this->availableCount = availableCount;
	}
	virtual void print(int pages) { printedCount += pages, availableCount -= pages; }
	virtual void show() = 0;
	string getModel() { return model; }
	string getManufacturer() { return manufacturer; }
	int getPrinted() { return printedCount; }
	int getAvailable() { return availableCount; }
};
class Inkjet : public Printer
{
	int availableInk;
public:
	Inkjet(string model, string manufacturer, int availableCount, int availableInk) : Printer(model, manufacturer, 0, availableCount)
	{
		this->availableInk = availableInk;
	}
	void printInkjet(int pages)
	{
		availableInk -= pages;
		print(pages);
	}
	int getInk()
	{
		return availableInk;
	}
	void show()
	{
		cout << getModel() << " ," << getManufacturer() << " ,남은 종이 " << getAvailable() << "장 ,남은 잉크 " << getInk() << endl;
	}
	void cannotPrint(bool& cannot, int pages)
	{
		if ((getAvailable() - pages) < 0 && (getInk() - pages) < 0)
			cannot = true, cout << "용지와 잉크가 부족하여 프린트할 수 없습니다." << endl;
		else if ((getAvailable() - pages) < 0)
			cannot = true, cout << "용지가 부족하여 프린트할 수 없습니다." << endl;
		else if ((getInk() - pages) < 0)
			cannot = true, cout << "잉크가 부족하여 프린트할 수 없습니다.." << endl;
		else
			cannot = false;
	}
};
class Laser : public Printer
{
	int availableToner;
public:
	Laser(string model, string manufacturer, int availableCount, int availableToner) : Printer(model, manufacturer, 0, availableCount)
	{
		this->availableToner = availableToner;
	}
	void printLaser(int pages)
	{
		availableToner -= pages;
		print(pages);
	}
	int getToner()
	{
		return availableToner;
	}
	void show()
	{
		cout << getModel() << " ," << getManufacturer() << " ,남은 종이 " << getAvailable() << "장 ,남은 토너 " << getToner() << endl;
	}
	void cannotPrint(bool& cannot, int pages)
	{
		if ((getAvailable() - pages) < 0 && (getToner() - pages) < 0)
			cannot = true, cout << "용지와 토너가 부족하여 프린트할 수 없습니다." << endl;
		else if ((getAvailable() - pages)  < 0)
			cannot = true, cout << "용지가 부족하여 프린트할 수 없습니다." << endl;
		else if ((getToner() - pages) < 0)
			cannot = true, cout << "토너가 부족하여 프린트할 수 없습니다." << endl;
		else
			cannot = false;
	}
};
int main(void)
{
	Inkjet* ink = new Inkjet("Officejet V40", "HP", 5, 10);
	Laser* laser = new Laser("SCX-6x45", "삼성전자", 3, 20);

	cout << "현재 작동중인 2대의 프린터는 아래와 같다." << endl;
	cout << "잉크젯 : ";
	ink->show();
	cout << "레이저 : ";
	laser->show();
	cout << endl;

	while (1)
	{
		char op;
		int printer, pages;
		cout << "프린터(1:잉크젯, 2:레이저)와 매수 입력>>";
		cin >> printer >> pages;

		if (printer == 1)
		{
			bool cannot;
			ink->cannotPrint(cannot, pages);
			if (!cannot)
			{
				ink->printInkjet(pages);
				cout << "프린트하였습니다." << endl;
				ink->show();
				laser->show();
			}
			cout << "계속 프린트 하시겠습니까?(y/n)>>";
			cin >> op;
			if (op == 'n')
				break;
		}
		else if (printer == 2)
		{
			bool cannot;
			laser->cannotPrint(cannot, pages);
			if (!cannot)
			{
				laser->printLaser(pages);
				cout << "프린트하였습니다." << endl;
				ink->show();
				laser->show();
			}
			cout << "계속 프린트 하시겠습니까?(y/n)>>";
			cin >> op;
			if (op == 'n')
				break;
		}
		else
		{
			cout << "프린터를 잘못 선택했습니다." << endl;
		}
		cout << endl;
	}
	delete ink;
	delete laser;
}





728x90