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

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

꾸준함. 2017. 7. 18. 23:01

[Exercises 1]

/*

Modify Program 1.5 so that it throws an exception of type int.

프로그램 1.5를 수정해서 int 자료형을 throw하도록 한다

The value of the thrown exception should be 1 if a, b, and c are all less than 0;

a, b, c가 모두 0보다 작다면 throw한 값은 1이 되어야 한다.

the value should be 2 if all three equal 0.

a, b, c가 모두 0이면 throw한 값은 2가 되어야 한다

When neither of these conditions is satisfied, no exception is thrown.

위에 언급한 두가지 조건이 아니라면 예외가 발생하지 않는다.

Write a main function that uses your modified code, catches the exception if thrown, and outputs a message

that depends on the value of the thrown exception

수정한 프로그램을 테스트 할 수 있도록(값이 throw가 되면 catch하고 메세지를 출력하도록) 메인문을 작성한다

*/

#include <iostream>

using namespace std;

 

int DivZero(int a, int b, int c)

{

        if (a < 0 && b < 0 && c < 0) //all less than 0

               throw 1;

        else if (a == 0 && b == 0 && c == 0) //all 0

               throw 2;

        return a + b*c + b / c;

}

 

int main(void)

{

        try

        {

               //cout << DivZero(-1, -1, -1) << endl;

               //cout << DivZero(0, 0, 0) << endl;

               cout << DivZero(1, 1, 1) << endl;

        }

        catch (int expn)

        {

               if (expn == 1)

               {

                       cout << "a, b, and c are all less than 0" << endl;

                       return 1;

               }

               else if (expn == 2)

               {

                       cout << "a, b, and c are all 0" << endl;

                       return 1;

               }

        }

        return 0;

}


[Exercises 2]

/*

Write a C++ function to return the sum of the first n numbers in the integer array a.

배열 a에 포함된 숫자 중 처음 n개의 숫자들의 합을 반환하는 c++ 함수를 작성한다.

Your function should throw an exception in case n<0.

이 함수에서 만약 n 0보다 작다면 예외를 throw 해야한다.

Test your code

메인문을 작성해서 함수가 잘 작동하는지 확인한다.

*/

#include <iostream>

using namespace std;

 

int Sum(int *arr, int n)

{

        int sum = 0;

        if (n <= 0)

               throw n;

        for (int i = 0; i < n; i++)

               sum += arr[i];

        return sum;

}

 

int main(void)

{

        int *arr;

        int n;

        int length;

        cout << "배열의 크기는?";

        cin >> length;

        arr = new int[length];

        for (int i = 0; i < length; i++)

               arr[i] = i + 1;

        cout << "n 값 입력: ";

        cin >> n;

        try

        {

               cout << "합계: " << Sum(arr, n) << endl;

        }

        catch (int expn)

        {

               cout << "n의 값은 0보다 커야한다" << endl;

               cout << "따라서 " << expn << " n의 값이 될 수 없다" << endl;

               return 1;

        }

        return 0;

}


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


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

반응형