반응형

9.4> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 WhileLoopAdder, DoWhileLoopAdder 클래스를 작성하라. While , do-while 문을 이용하여 합을 구하도록 calculate() 함수를 각각 작성하면 된다.

<코드>

#include<iostream>

#include<string>

 

using namespace std;

 

class LoopAdder{  //추상 클래스

      string name;  //루프의 이름

      int x, y, sum;  //x에서 y까지의 합은 sum

      void read();  //x, y 값을 읽어 들이는 함수

      void write();  //sum 출력하는 함수

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(){ //x, y 입력

      cout << name << ":" << endl;

      cout << "처음 수에서 두번째 수까지 더합니다. 수를 입력하세요 >>";

      cin >> x >> y;

}

 

void LoopAdder::write(){

     cout << x << "에서 " << y << "까지의 = " << sum << " 입니다" << endl;

     //결과 sum 출력

}

 

void LoopAdder::run(){

      read();  //x, y 읽는다.

      sum = calculate();  //루프를 돌면서 계산한다.

      write();  //결과 sum 출력한다.

}

 

 

 

class WhileLoopAdder : public LoopAdder{

public:

        WhileLoopAdder(string name);

protected:

        virtual int calculate();

};

WhileLoopAdder::WhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int WhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        while(check<=to){sum+=check;check++;} //check to이하이면 실행

        return sum;

}

 

class DoWhileLoopAdder : public LoopAdder{

public:

        DoWhileLoopAdder(string name);

protected:

        virtual int calculate();

};

DoWhileLoopAdder::DoWhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int DoWhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        do{sum+=check;check++;}while(check<=to); //무조건 처음은 실행, 그이후 check to 이하일때만 실행

        return sum;

}

 

int main(void){

        WhileLoopAdder whileLoop("While Loop");

        DoWhileLoopAdder doWhileLoop("Do while Loop");

 

        whileLoop.run();

        doWhileLoop.run();

        return 0;

}

 

 

<결과창>


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

추상 클래스 상속 (Int Stack)  (0) 2017.12.31
논리 게이트  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31

+ Recent posts