C++/Fundamentals of Data Structures in C++(Horowitz)

C++ Fundamentals of Data Structures(C++ 자료구조론) 2.1 연습문제

꾸준함. 2017. 7. 25. 15:39

[Exercises 1]

/*

Overload operator< for class Rectangle such that r<s if and only if the area of r is less than that of s.

Rectangle 클래스에서 < 연산자를 오버로드 하되 s의 넓이가 r의 넓이보다 클 때 적용되도록 오버로드해라

*/

#include <iostream>

using namespace std;

 

class Rectangle

{

private:

        int xLow, yLow;

        int height, width;

public:

        Rectangle(int x = 0, int y = 0, int h = 0, int w = 0) :xLow(x), yLow(y), height(h), width(w)

        {

        }

        ~Rectangle()

        {

        }

 

        int GetHeight()

        {

               return height;

        }

        int GetWidth()

        {

               return width;

        }

       

        int GetArea()

        {

               return (height*width); //넓이 반환

        }

 

        bool operator<(Rectangle &s)//연산자 오버로딩

        {

               if (GetArea()<s.GetArea())

                       return true;

               else

                       return false;

        }

        friend ostream &operator<<(ostream &os, Rectangle &r);

};

 

ostream &operator<<(ostream &os, Rectangle &r)

{

        os << "중심: " << r.xLow << " " << r.yLow << endl;

        os << "높이: " << r.height << endl;

        os << "너비: " << r.width << endl;

        os << "넓이: " << r.GetArea() << endl;

        return os;

}

 

int main(void)

{

        Rectangle r(1, 1, 3, 4);

        Rectangle s(3, 3, 4, 4);

 

        cout << "첫 번째 직사각형 r 소개" << endl << r << endl;

        cout << endl << "두 번째 직사각형 s 소개" << endl << s << endl;

 

        cout << "둘 중 넓이가 더 큰 직사각형은?" << endl;

        if (r < s)

               cout << "s의 넓이가 r의 넓이보다 크다" << endl;

        else

               cout << "r의 넓이가 s의 넓이보다 크다" << endl;

        return 0;

}

 



[Exercises 2]

/*

Write and test C++ code for the class MyRectangle, which is an enhanced version of the class Rectangle(Program 2.1)

Program 2.1에서 정의한 Rectangle 클래스보다 한층 발전된 MyRectangle 클래스를 작성하고 작동시켜본다.

In addition to the data members listed in Program 2.1, MyRectangle has the data member color.

MyRectangle Program 2.1에서 작성한 데이터 멤버에서 color 멤버가 추가되었다.

You must include functinos to change as well as to return the value of each data member and functions to return the area and permiter of a rectangle

각 데이터 멤버의 값과 넓이 그리고 둘레길이를 반환하는 함수를 작성해야하고 데이터멤버를 수정하는 함수도 작성해야한다.

The operators << and >> should be overloaded to work with rectangles

<<, >> 연산자를 오버로드 시켜야한다.

*/

#include <iostream>

#include <cstring>

using namespace std;

 

class MyRectangle

{

private:

        int xLow, yLow;

        int height, width;

        char *color; //추가된 부분

public:

        MyRectangle(int x = 0, int y = 0, int h = 0, int w = 0, char *c="흰색") :xLow(x), yLow(y), height(h), width(w)

        {

               int len;

               len = strlen(c);

               color = new char[len];

               strcpy(color, c);

        }

        ~MyRectangle()

        {

        }

 

        int GetHeight()

        {

               return height;

        }

        int GetWidth()

        {

               return width;

        }

 

        int GetArea()

        {

               return (height*width); //넓이 반환

        }

 

        int GetPerimeter()

        {

               return 2 * (height + width);

        }

       

        bool operator<(MyRectangle &s)//연산자 오버로딩

        {

               if (GetArea()<s.GetArea())

                       return true;

               else

                       return false;

        }

        friend ostream &operator<<(ostream &os, MyRectangle &r);

        friend istream &operator>>(istream &is, MyRectangle &r);

};

 

ostream &operator<<(ostream &os, MyRectangle &r)

{

        os << "중심: " << r.xLow << " " << r.yLow << endl;

        os << "높이: " << r.height << endl;

        os << "너비: " << r.width << endl;

        os << "색깔: " << r.color << endl;

        os << "넓이: " << r.GetArea() << endl;

        os << "둘레길이: " << r.GetPerimeter() << endl;

        return os;

}

 

istream &operator>>(istream &is, MyRectangle &r)

{

        char c[20];

        cout << "바꿀 중점: ";

        is >> r.xLow >> r.yLow;

        cout << "바꿀 높이: ";

        is >> r.height;

        cout << "바꿀 너비: ";

        is >> r.width;

        cout << "바꿀 색깔: ";

        cin >> c;

        int len = strlen(c);

        r.color = new char[len];

        strcpy(r.color, c);

        return is;

}

 

int main(void)

{

        MyRectangle r(1, 1, 3, 4, "빨간색");

        MyRectangle s(3, 3, 4, 4, "파란색");

 

        cout << "첫 번째 직사각형 r 소개" << endl << r << endl;

        cout << endl << "두 번째 직사각형 s 소개" << endl << s << endl;

 

        cout << endl;

        cout << "첫 번째 직사각형 r 수정" << endl;

        cin >> r;

        cout << "수정된 첫 번째 직사각형 r 소개" << endl << r << endl;

        cout << endl;

        cout << "두 번째 직사각형 s 수정" << endl;

        cin >> s;

        cout << endl << "수정된 두 번째 직사각형 s 소개" << endl << s << endl;

 

        return 0;

}

 


[Exercises 3]

/*

Write and test code for the C++ class Currency, which represents currency objects.

화폐를 표현하는 Currency 클래스를 작성하고 테스트해보자.

Each currency object hass two data members $ and cents, where cents is an integer between 0 and 99.

Currency 오브젝트는 $ 0~99 사이의 숫자를 가지는 cents를 데이터 멤버로 갖는다.

You must include functions to set and return the data members, add and subtract currency objects, to multiply a currency object by numbers such as 2, 2.5 and so on.

당신은 데이터 멤버를 설정하거나 반환하는 함수를 작성하고, 화폐 오브젝트들을 더하거나 빼거나 곱하는 함수를 작성해야한다.(예를 들어 2, 2.5 등등)

The operators << and >> should be overloaded to work with currency objects.

<<, >> 연산자가 오버로딩되어야한다,

*/

#include <iostream>

using namespace std;

 

class Currency

{

private:

        int dollar;

        int cent;

public:

        Currency(int a = 0, int b = 0) :dollar(a), cent(b)

        {

        }

        Currency operator+(const Currency &r)

        {

               int totalDollar = dollar + r.dollar;

               int totalCent = cent + r.cent;

               if (totalCent > 99)

               {

                       totalDollar++;

                       totalCent -= 100;

               }

               return Currency(totalDollar, totalCent);

        }

        Currency operator-(const Currency &r)

        {

               int totalDollar = dollar - r.dollar;

               int totalCent = cent - r.cent;

               if (totalCent < 0)

               {

                       totalDollar--;

                       totalCent += 100;

               }

               if (totalDollar < 0)

               {

                       cout << "파산" << endl;

                       totalDollar = 0;

                       totalCent = 0;

               }

               return Currency(totalDollar, totalCent);

        }

        Currency operator*(const Currency &r)

        {

               int totalDollar = dollar*r.dollar;

               int totalCent = cent*r.cent;

               while (totalCent > 100)

               {

                       totalDollar--;

                       totalCent -= 100;

               }

               return Currency(totalDollar, totalCent);

        }

 

        friend ostream &operator<<(ostream &os, Currency &r);

        friend istream &operator>>(istream &is, Currency &r);

};

 

ostream &operator<<(ostream &os, Currency &r)

{

        os << "달러: " << r.dollar << endl;

        os << "센트: " << r.cent << endl;

        return os;

}

 

istream &operator>>(istream &is, Currency &r)

{

        cout << "달러 변경: ";

        is >> r.dollar;

        cout << "센트 변경(0~99): ";

        is >> r.cent;

        while (r.cent < 0 || r.cent>99)

        {

               cout << "재입력(0~99): ";

               is >> r.cent;

        }

        return is;

}

 

int main(void)

{

        Currency cur;

        cout << "cur 화폐 입력" << endl;

        cin >> cur;

        cout << endl;

 

        cout << "cur 내용 출력" << endl;

        cout << cur;

 

        Currency cur2(3, 3); //3달러 3센트

        cout << "cur2 내용 출력" << endl;

        cout << cur2;

        cout << "cur1 cur2 덧셈 결과" << endl;

        Currency cur3 = cur + cur2;

        cout << cur3;

        cout << "cur1 cur2 뺄셈 결과" << endl;

        Currency cur4 = cur - cur2;

        cout << cur4;

        cout << "cur1 cur2 곱셈 결과" << endl;

        Currency cur5 = cur*cur2;

        cout << cur5;

 

}


[Exercises 4]

/*

Implement a class Complex, which represents the Complex Number data type.

복소수를 나타내는 Complex 클래스를 구현한다.

Implement the following operations:

다음의 기능을 구현한다.

(a) A constructor(including a default constructor which creates the complex number 0+0i)

(a) 디폴트 생성자를 포함한 생성자를 구현

(b) Overload operator+ to add two complex numbers

(b) 연산자 +를 오버로드해서 복소수의 합을 반환하도록 한다

(c) Overload operator* to multiply two complex numbers

(c) 연산자 *를 오버로드해서 복소수의 곱을 반환하도록 한다

(d) Overload << and >> to print and read complex numbers.

(d) <<, >> 연산자를 오버로드해서 복소수의 값을 설정하고 출력한다.

*/

#include <iostream>

using namespace std;

 

class Complex

{

private:

        int Real;

        int UnReal;

public:

        Complex(int a = 0, int b = 0) :Real(a), UnReal(b) //(a)

        {

        }

        Complex operator+(const Complex &r) //(b)

        {

               return Complex(Real + r.Real, UnReal + r.UnReal);

        }

        Complex operator*(const Complex &r) //(c)

        {

               return Complex(Real*r.Real - UnReal*r.UnReal, Real*r.UnReal + UnReal*r.Real);

        }

 

        friend ostream &operator<<(ostream &os, Complex &r); //(d)

        friend istream &operator>>(istream &is, Complex &r); //(d)

};

 

ostream &operator<<(ostream &os, Complex &r)

{

        os << "(" << r.Real << " + " << r.UnReal << "i)" << endl;

        return os;

}

 

istream &operator>>(istream &is, Complex &r)

{

        cout << "실수부 입력: ";

        is >> r.Real;

        cout << "허수부 입력: ";

        is >> r.UnReal;

        return is;

}

 

int main(void)

{

        Complex c1(3, 4);

        Complex c2; //디폴트

       

        cout << "c1 클래스 출력" << endl;

        cout << c1;

        cout << "c2 클래스 내용 입력" << endl;

        cin >> c2;

        cout << "c2 클래스 출력" << endl;

        cout << c2;

 

        cout << "합 출력" << endl;

        Complex c3 = c1 + c2;

        cout << c3;

 

        cout << "곱 출력" << endl;

        Complex c4 = c1*c2;

        cout << c4;

 

        return 0;

}


[Exercises 5]

/*

Implement a class Quadratic that represents 2-degree polynomials i.e, polynomials of type ax^2+bx+c

이차방정식(예를 들어 ax^2+bx+c)를 표현하는 Quadratic 클래스를 구현한다.

Your class will require three data members corresponding to a, b, and c

클래스에는 a, b, c 값에 대응할 세개의 데이터 멤버가 필요하다.

Implement the followiing operations

다음의 기능들을 구현하라

(a) A constructor(including a default constructor which creates the 0 polynomial)

(a) 0개의 다항식을 생성하는 디폴트 생성자를 포함한 생성자

(b) Overload operator+ to add two polynomials of degree 2

(b) 2개의 이차다항식을 더하기 위한 + 연산자 오버로드

(c) Overload << and >> to print and read polynomials

(c) <<, >>  연산자를 오버로드해서 다항식 값을 입력하거나 출력하라

(d) A function Eval that computes the value of a polynomail for a given value of x

(d) 특정 x를 대입했을 때 결과를 출력해줄 Eval 함수

(e) A function that computes the two solutions of the equation ax^2+bx+c=0.

(e) 두개의 근을 구해줄 함수

*/

#include <iostream>

#include <cmath>

using namespace std;

 

class Quadratic

{

private:

        int a;

        int b;

        int c;

public:

        Quadratic(int x = 0, int y = 0, int z = 0) :a(x), b(y), c(z)//(a)

        {

        }

        Quadratic operator+(const Quadratic &q) //(b)

        {

               return Quadratic(a + q.a, b + q.b, c + q.c);

        }

        int Eval(int x) //(d)

        {

               return (a*x*x) + (b*x) + (c);

        }

 

        void Solution(const Quadratic &q) //(e)

        {

               int x1 = (-b + sqrt(b*b - 4 * a*c)) / (2 * a); //근의 공식

               int x2 = (-b - sqrt(b*b - 4 * a*c)) / (2 * a);

               cout << "첫 번째 근: " << x1 << endl;

               cout << "두 번째 근: " << x2 << endl;

        }

 

        friend ostream &operator<<(ostream &os, const Quadratic &q); //(c)

        friend istream &operator>>(istream &is, Quadratic &q); //(c)

};

 

ostream &operator<<(ostream &os, const Quadratic &q)

{

        os << q.a << "x^2 + " << q.b << " x + " << q.c << endl;

        return os;

}

 

istream &operator>>(istream &is, Quadratic &q)

{

        cout << "x^2의 항: ";

        is >> q.a;

        cout << "x의 항: ";

        is >> q.b;

        cout << "상수: ";

        is >> q.c;

        return is;

}

 

int main(void)

{

        Quadratic q1(1, -4, 3);

        Quadratic q2; //디폴트

 

        cout << "q1 다항식 출력" << endl;

        cout << q1 << endl;

        cout << "q1 다항식에 2를 대입할 경우 값: " << q1.Eval(2) << endl;

        cout << "q1 다항식의 두 근: " << endl;

        q1.Solution(q1);

        cout << "q2 다항식 입력" << endl;

        cin >> q2;

        cout << "q2 다항식 출력" << endl;

        cout << q2;

 

        Quadratic q3 = q1 + q2;

        cout << "q1 q2의 합" << endl;

        cout << q3;

}



[참고] Fundamentals of Data Structures in C++(Horowitz, Sahni, Mehta) 원서


*영어로 적혀있는 문제를 제가 의역한 것이기 때문에 오역이 있을 수 있습니다. 양해 부탁드립니다.


반응형