Programming Language/C,C++

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

TwinParadox 2017. 10. 28. 00:30
728x90

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

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

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

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

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



실습문제 1. add() 함수를 호출하는 main() 함수는 다음과 같다. add() 함수를 중복 작성하고, 프로그램을 완성하라. 디폴트 매개 변수를 가진 하나의 add() 함수를 작성하고 프로그램을 완성하라.


#include <iostream>
using namespace std;
/* 1 */
/*
int add(int* arr1, int size)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += arr1[i];
	return sum;
}
int add(int* arr1, int size, int* arr2)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += arr1[i] + arr2[i];
	return sum;
}
int main(void)
{
	int a[] = { 1,2,3,4,5 };
	int b[] = { 6,7,8,9,10 };
	int c = add(a, 5);
	int d = add(a, 5, b);
	cout << c << endl;
	cout << d << endl;
}
*/
/* 2 */
int add(int* arr1, int size=5)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += arr1[i];
	return sum;
}
int add(int* arr1, int* arr2, int size=5)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += arr1[i] + arr2[i];
	return sum;
}
int main(void)
{
	int a[] = { 1,2,3,4,5 };
	int b[] = { 6,7,8,9,10 };
	int c = add(a, 5);
	int d = add(a, b, 5);
	cout << c << endl;
	cout << d << endl;
}




실습문제 2. Person 클래스의 객체를 생성하는 main() 함수는 다음과 같다. 생성자를 중복 작성하고 프로그램을 완성하라. 디폴트 매개 변수를 가진 하나의 생성자를 작성하고 프로그램을 완성하라.


#include <iostream>
#include <string>
using namespace std;
class Person
{
	int id;
	double weight;
	string name;
public:
	// (1)
	/*
	Person() { id = 1, weight = 20.5, name = "Grace"; }
	Person(int id, string name) { this->id = id, this->name = name, weight = 20.5; }
	Person(int id, string name, double weight) { this->id = id, this->name = name, this->weight = weight; }
	*/
	// (2)
	Person(int id = 1, string name = "Grace", double weight = 20.5) { this->id = id, this->name = name, this->weight = weight; }
	void show() { cout << id << ' ' << weight << ' ' << name << endl; }
};
int main(void)
{
	Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
	grace.show();
	ashley.show();
	helen.show();
}




실습문제 3. 함수 big()을 호출하는 경우는 다음과 같다. big() 함수를 2개 중복하여 작성하고 프로그램을 완성하라. 디폴트 매개 변수를 가진 하나의 함수로 big()을 작성하고 프로그램을 완성하라.


#include <iostream>
#include <string>
using namespace std;
// 1
/*
int big(int a, int b)
{
	int max = a < b ? b : a;
	if (max < 100)
		return max;
	else
		return 100;
}
int big(int a, int b, int c)
{
	int max = a < b ? b : a;
	if (max < c)
		return max;
	else
		return c;
}
*/
// 2
int big(int a, int b, int c = 100)
{
	int max = a < b ? b : a;
	if (max < c)
		return max;
	else
		return c;
}
int main()
{
	int x = big(3, 5);
	int y = big(300, 60);
	int z = big(30, 60, 50);
	cout << x << ' ' << y << ' ' << z << endl;
}




실습문제 4. 다음 클래스에 중복된 생성자를 디폴트 매개 변수를 가진 하나의 생성자로 작성하고 테스트 프로그램을 작성하라.


#include <iostream>
using namespace std;
class MyVector
{
	int* mem;
	int size;
public:
	MyVector(int n = 100, int val = 0);
	~MyVector() { delete[] mem; }
	void show();
};
MyVector::MyVector(int n, int val)
{
	mem = new int[n];
	size = n;
	for (int i = 0; i < size; i++)
		mem[i] = val;
}
void MyVector::show()
{
	cout << size << endl;
	for (int i = 0; i < size; i++)
		cout << mem[i] << ' ';
	cout << endl;
}
int main(void)
{
	MyVector v1, v2(10, 5);
	v1.show();
	v2.show();
}




실습문제 5. 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라. ArrayUtility를 활용하는 main()은 다음과 같다.


#include <iostream>
using namespace std;
class ArrayUtility
{
public:
	static void intToDouble(int source[], double dest[], int size);
	static void doubleToInt(double source[], int dest[], int size);
};
void ArrayUtility::intToDouble(int source[], double dest[], int size)
{
	for (int i = 0; i < size; i++)
		dest[i] = (double)source[i];
}
void ArrayUtility::doubleToInt(double source[], int dest[], int size)
{
	for (int i = 0; i < size; i++)
		dest[i] = (int)source[i];
}
int main()
{
	int x[] = { 1,2,3,4,5 };
	double y[5];
	double z[] = { 9.9, 8.8, 7.7, 6.6, 5.6 };

	ArrayUtility::intToDouble(x, y, 5);
	for (int i = 0; i < 5; i++)
		cout << y[i] << ' ';
	cout << endl;

	ArrayUtility::doubleToInt(z, x, 5);
	for (int i = 0; i < 5; i++)
		cout << x[i] << ' ';
	cout << endl;
}




실습문제 6. 동일한 크기의 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility2 클래스를 만들고, 이 클래스를 이용하여 아래 결과와 같이 출력되도록 프로그램을 완성하라.


#include <iostream>
using namespace std;
class ArrayUtility2
{
public:
	static int* concat(int s1[], int s2[], int size);
	static int* remove(int s1[], int s2[], int size, int& retSize);
};
int* ArrayUtility2::concat(int s1[], int s2[], int size)
{
	int* arr = new int[size * 2];
	for (int i = 0; i < size; i++)
		arr[i] = s1[i];
	for (int i = size; i < size * 2; i++)
		arr[i] = s2[i - size];
	return arr;
}
int* ArrayUtility2::remove(int s1[], int s2[], int size, int& retSize)
{
	int* arr = new int[size], idx = 0;
	for (int i = 0; i < size; i++)
	{
		bool check = false;
		for (int j = 0; j < size; j++)
			if (s1[i] == s2[j])
				check = true;
		if (!check)
			arr[idx++] = s1[i];
	}
	retSize = idx;
	return arr;
}
int main(void)
{
	int size = 5, retSize;
	int *x, *y;
	int *result1, *result2;
	x = new int[size], y = new int[size];
	cout << "정수를 " << size << " 개를 입력하라. 배열 x에 삽입한다>>";
	for (int i = 0; i < size; i++)
		cin >> x[i];
	cout << "정수를 " << size << " 개를 입력하라. 배열 y에 삽입한다>>";
	for (int i = 0; i < size; i++)
		cin >> y[i];
	result1 = ArrayUtility2::concat(x, y, size);
	cout << "합친 정수 배열을 출력한다" << endl;
	for (int i = 0; i < size * 2; i++)
		cout << result1[i] << ' ';

	result2 = ArrayUtility2::remove(x, y, size, retSize);
	cout << endl << "배열 x[]에서 y[]를 뺀 결과를 출력한다. 개수는 " << retSize << endl;
	for (int i = 0; i < retSize; i++)
		cout << result2[i] << ' ' << endl;
}




실습문제 7. 다음과 같은 static 멤버를 가진 Random 클래스를 완성하라. 그리고 Random 클래스를 이용하여 다음과 같이 랜덤한 값을 출력하는 main() 함수도 작성하라. main()에서 Random 클래스의 seed() 함수를 활용하라.


#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
class Random
{
public:
	static void seed() { srand((unsigned)time(0)); }
	static int nextInt(int min = 0, int max = 32767);
	static char nextAlphabet();
	static double nextDouble();
};
int Random::nextInt(int min, int max)
{
	return rand() % max + min;
}
char Random::nextAlphabet()
{
	int choice = rand() % 2;
	if (choice)
		return (char)(rand() % 26 + 65);
	else
		return (char)(rand() % 26 + 97);
}
double Random::nextDouble()
{
	return ((double)rand() / (double)32767);
}
int main(void)
{
	int min = 1, max = 100, size = 10;
	Random::seed();
	cout << min << "에서 " << max << "까지 랜덤한 정수 " << size << "개를 출력합니다." << endl;
	for (int i = 0; i < size; i++)
		cout << Random::nextInt(min, max) << ' ';
	cout << endl;

	cout << "알파벳을 램덤하게 " << size << "개를 출력합니다." << endl;
	for (int i = 0; i < size; i++)
		cout << Random::nextAlphabet() << ' ';
	cout << endl;

	cout << "랜덤한 실수를 " << size << "개를 출력합니다." << endl;
	for (int i = 0; i < size; i++)
		cout << Random::nextDouble() << ' ';
	cout << endl;
}




실습문제 8. 디버깅에 필요한 정보를 저장하는 Trace 클래스를 만들어보자. 저자의 경험에 의하면, 멀티 태스크 프로그램을 개발하거나, 특별한 환경에서 작업할 때, Visual Studio의 디버거와 같은 소스 레벨 디버거를 사용하지 못하는 경우가 더러 있었고, 이때 실행 도중 정보를 저장하기 위해 Trace 클래스를 사용하였다. Trace 클래스를 활용하는 다음 프로그램과 결과를 참고하여 Trace 클래스를 작성하고 전체 프로그램을 완성하라. 디버깅 정보는 100개로 제한한다.


#include <iostream>
#include <string>
using namespace std;
class Trace
{
	static string list[100][2];
	static int idx;
public:
	static void put(string tag, string info);
	static void print(string tag="");
};
void Trace::put(string tag, string info)
{
	if (idx + 1 >= 100)
	{
		cout << "용량 초과" << endl;
		return;
	}
	list[idx][0] = tag, list[idx][1] = info;
	idx++;
}
void Trace::print(string tag)
{
	if (tag == "")
	{
		cout << "------ 모든 Trace 정보를 출력합니다. ------\n";
		for (int i = 0; i < idx; i++)
			cout << list[i][0] << ':' << list[i][1] << '\n';
	}
	else
	{
		cout << "------ " << tag << "태그의 Trace 정보를 출력합니다. ------\n";
		for (int i = 0; i < idx; i++)
			if (list[i][0] == tag)
				cout << list[i][0] << ':' << list[i][1] << '\n';
	}
}
void f()
{
	int a, b, c;
	cout << "두 개의 정수를 입력하세요>>";
	cin >> a >> b;
	Trace::put("f()", "정수를 입력 받았음");
	c = a + b;
	Trace::put("f()", "합 계산");
	cout << "합은 " << c << endl;
}
int Trace::idx = 0;
string Trace::list[100][2] = {};
int main(void)
{
	Trace::put("main()", "프로그램을 시작합니다.");
	f();
	Trace::put("main()", "종료");

	Trace::print("f()");
	Trace::print();
}
728x90
728x90