반응형

9.5> 디지털 회로에서 기본적인 게이트로 OR 게이트, AND 게이트, XOR 게이트 등이 있다. 이들은 각각 두 입력 신호를 받아 OR 연산, AND 연산, XOR 연산을 수행한 결과를 출력한다. 이 게이트들을 각각 ORGate, XORGate, ANDGate 클래스로 작성하고자 한다. ORGate, XORGate, ANDGate 클래스가 AbstractGate를 상속받도록 작성하라.

<코드>

#include <iostream>

 

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:

        virtual bool operation();

};

bool ANDGate::operation(){return x&y;} //x y 비트and 연산 리턴

 

class ORGate : public AbstractGate{

public:

        virtual bool operation();

};

bool ORGate::operation(){return x|y;} //x y 비트or 연산 리턴

 

class XORGate : public AbstractGate{

public:

        virtual bool operation();

};

bool XORGate::operation(){return x^y;} //x y 비트xor연산 리턴

 

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); //불린 값을 "true", "false"문자열로 출력할 것을 지시

        cout<<and.operation()<<endl; //AND 결과는 false

        cout<<or.operation()<<endl; //OR 결과는 true

        cout<<xor.operation()<<endl; //XOR 결과는 true

        return 0;

}

 

 

<결과창>


반응형

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

추상 클래스 상속 (Int Stack)  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
반응형

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
반응형

9.3> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 ForLoopAdder 클래스를 작성하라. ForLoopAdder 클래스의 calculate() 함수는 for 문을 이용하여 합을 구한다.

<코드>

#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(){//결과 sum 출력

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

    }

 

void LoopAdder::run(){

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

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

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

}

 

class ForLoopAdder : public LoopAdder{

public:

        ForLoopAdder(string name);

protected:

        virtual int calculate();

};

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

int ForLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        for(int i=from;i<to+1;i++){sum+=i;}

        return sum; //from에서 to까지 순차적으로 더한 리턴

}

int main(void){

        ForLoopAdder forLoop("For Loop: ");

        forLoop.run();

        return 0;

}

 

<결과창>


반응형

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

논리 게이트  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
반응형

9.2> Converter 클래스를 상속받아 km mile(마일)로 변환하는 KmToMile 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

 

class KmToMile : public Converter{

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        KmToMile(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

KmToMile::KmToMile(double ratio,string from="Km",string to="Mile"):Converter(ratio){

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "Km" "Mile"

}

double KmToMile::convert(double src){return src/ratio;}

string KmToMile::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string KmToMile::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void){

        KmToMile toMile(1.609344); //1 mile 1.609344 Km

        toMile.run();

        return 0;

}

 

<결과창>

                                   


반응형

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

while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
반응형

9.1> Converter 클래스를 상속받아 달러를 원화로 환산하는 WonToDollar 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

class WonToDollar : public Converter { //컨버터 클래스를 상속받은 원투달라 클래스

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        WonToDollar(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

WonToDollar::WonToDollar(double ratio, string from = "", string to = "달러") : Converter(ratio) {

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "" "달러"

}

double WonToDollar::convert(double src) {

        return (src/ratio); //src/ratio 리턴, 컨버트 함수 오버라이딩

}

string WonToDollar::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string WonToDollar::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void) {

        WonToDollar wd(1010); //비율을 1010으로 해서 객체 생성

        wd.run(); //컨버팅 실행

        return 0;

}

 

<결과창>

                                

   


반응형

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

ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
반응형

8.8> 다음 그림과 같은 상속 구조를 갖는 클래스를 설계한다. 모든 프린터는 모델명(model), 제조사(manufacturer), 인쇄 매수(printedCount), 인쇄 종이 잔량(availableCount)을 나타내는 정보와 print(int pages) 멤버 함수를 가지며, print()가 호출할 때마다 pages 매의 용지를 사용한다. 잉크젯 프린터는 잉크 잔량(availableInk) 정보와 printInkJet(int pages) 멤버 함수를 추가적으로 가지며, 레이저 프린터는 토너 잔량(availableToner) 정보와 역시 printLaser(int pages) 멤버 함수를 추가적으로 가진다. 각 클래스에 적절한 접근 지정으로 멤버 변수와 함수, 생성자, 소멸자를 작성하고, 다음과 같이 실행되도록 전체 프로그램을 완성하라. 잉크젯 프린터 객체와 레이저 프린터 객체를 각각 하나만 동적 생성하여 시작한다.

<코드>

#include <iostream>

#include <string>

 

using namespace std;

 

class Printer { //프린터 클래스

protected:

        string model; //모델명 스트링

        string manufacturer; //제조사명 스트링

        int printedcount; // 출력된 매수

        int availableCount; // 앞으로 출력 가능한 매수

        int print(int pages); //프린트 원형 함수

        Printer(string model, string manufacturer, int availableCount); //생성자

        void show(); // 화면 출력 함수

};

class InkjetPrinter : public Printer { //프린터를 상속받은 잉크젯 프린터 클래스

private:

        int availableInk; //잉크잔량

public:

        InkjetPrinter(string model, string manufacturer, int availableCount,int availableInk); //생성자

        void printInkJet(int pages); //잉크젯 프린트 함수

        void inkjetshow(); //잉크젯 화면 출력 함수

};

class LaserPrinter : public Printer { //프린터를 상속받은 레이저 프린터 클래스

private:

        float availableToner; //토너잔량

public:

        LaserPrinter(string model, string manufacturer, int availableCount, float availableToner); //생성자

        void printLaser(int pages); //레이저 프린트 함수

        void lasershow(); //레이저 화면 출력 함수

};

Printer::Printer(string model, string manufacturer, int availableCount) {

        this->model = model;

        this->manufacturer = manufacturer;

        this->printedcount = 0; //객체 생성시 한장도 안뽑았으므로 0

        this->availableCount = availableCount;

}

int Printer::print(int pages) {

        if (availableCount - pages < 0) { cout << "용지가 부족하여 프린트 없습니다." << endl; return 0; }

        else { availableCount -= pages; printedcount += pages;  return 1; }

} //사용가능한 용지보다 뽑아야하는 용지 수가 많으면 fail, 아니면 success 이때는 사용가능 페이지를 사용한 만큼 - 해준다. 그리고 사용한 페이지를 +해준다.

        //리턴 타입을 정해준 이유는 아래 프린트잉크젯이나 프린트레이저에서 프린트가 가능 때만 if문이 실행되게 하기 위해서 그렇다.

 

void Printer::show() {

        cout << this->model << ", " << this->manufacturer << ", " << "남은 종이" << this->availableCount << "";

} //모델명, 제조사명, 남은종이 출력

 

InkjetPrinter::InkjetPrinter(string model, string manufacturer, int availableCount, int availableInk) : Printer(model, manufacturer, availableCount) {

        this->availableInk = availableInk;} //프린터 생성자와 동시에 사용가능잉크 입력

void InkjetPrinter::printInkJet(int pages) {if (print(pages)) {

        if(availableInk-pages<0){ cout << "잉크가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //잉크 부족시 에러

        else {cout << "프린트하였습니다." << endl; availableInk -= pages;} }} //페이지 수만큼 출력가능하면 잉크 그만큼 -해줌.

void InkjetPrinter::inkjetshow() {

        show(); cout << ", 남은 잉크 " << this->availableInk << endl;} //print show 실행 남은 잉크 출력

 

LaserPrinter::LaserPrinter(string model, string manufacturer, int availableCount, float availableToner) : Printer(model, manufacturer, availableCount) {

        (this->availableToner) = (float)availableToner; } //프린터 생성자와 동시에 사용가능토너 입력

 

void LaserPrinter::printLaser(int pages) { if (print(pages)) {

        if((float)(availableToner*2)-(float)pages<0){ cout << "토너가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //토너 부족시 에러

        else {cout << "프린트하였습니다." << endl; (float)availableToner -= ((float)pages/2);} } } // 페이지 수만큼 출력가능하면 토너 그것의 1/2만큼 - 해줌.

void LaserPrinter::lasershow() {

        show(); cout << ", 남은 잉크 " << (float)(this->availableToner) << endl;} //print show 실행 남은 토너 출력

 

int main(void) {

        char check = 0; // check y/n 나타낸다.

        InkjetPrinter ip("Officejet V40", "HP", 20, 10); // 잉크젯프린터 ip 생성

        LaserPrinter lp("SCX-6x45", "삼성전자", 30, 10.0); // 레이저프린터 lp 생성

        cout << "현재 작동 중인 2 대의 프린터는 아래와 같다." << endl;

        cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

        while (1) {

               cout << "프린터(1:잉크젯, 2:레이저) 매수 입력>> ";

               int which = 0; int pg = 0; //which 잉크젯과 레이저를 구분

               cin >> which >> pg; cin.ignore(100, '\n'); //개행문자 삭제를 위하여 ignore 사용

               if (which == 1) { //잉크젯이면

                       ip.printInkJet(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                      

                      

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check=cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y'||check=='n') { break; } //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check=='y') continue; else if (check=='n') break//y 루프 처음으로 n이면 브레이크

               }

               else if (which == 2) { //레이저면

                       lp.printLaser(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check = cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y' || check == 'n') { break; }  //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check == 'y') continue; else if (check == 'n') break; //y 루프 처음으로 n이면 브레이크

               }

               else { cout << "잘못된 입력입니다." << endl; continue; } //which 1이나 2가아니면 출력되는 에러

        }

        return 0;

}

 

 

 

<결과창>


반응형

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

KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
반응형

8.7> 아래와 같은 BaseMemory 클래스를 상속받는 ROM(Read Only Memory), RAM 클래스를 작성하라. BaseMemory에 필요한 코드를 수정 추가하여 적절히 완성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseMemory { //베이스메모리 클래스

private:

        char *mem; //캐릭터 동적 배열을 가리킬 포인터 mem

protected:

        BaseMemory(int size) { mem = new char[size]; } //생성자 mem size만큼의 캐릭터 동적 배열 할당

        void burn(int index, char value);

public:

        char read(int index);

 

};

class ROM : public BaseMemory { //베이스메모리를 상속받은 롬 클래스

public:

        ROM(int memsize, char *arr, int arrsize);

};

 

class RAM : public BaseMemory { //베이스메모리를 상속받은 램 클래스

public:

        RAM(int memsize);

        void write(int i, char value);

};

 

void BaseMemory::burn(int index, char value) { mem[index] = value; } //mem 배열의 해당 index value 삽입

 

char BaseMemory::read(int index) { return mem[index]; } //mem 배열의 해당 index 원소 리턴

 

ROM::ROM(int memsize, char *arr, int arrsize) : BaseMemory(memsize) { //롬 생성자, 베이스 메모리 생성자 실행하고

        for (int i = 0; i < arrsize; i++) { burn(i, arr[i]); } //arr이 가리키는 배열의 원소 ROM에 굽는다.

}

RAM::RAM(int memsize) : BaseMemory(memsize) {} //단순히 memsize의 캐릭터 동적 배열만 할당한다.(베이스메모리 컨스트럭터와 동일)

 

void RAM::write(int i, char value) { burn(i, value); } //램에 존재하는 캐릭터 배열 인덱스 i value값을 삽입한다.

 

int main(void) {

        char x[5] = { 'h','e','l','l','o' }; //캐릭터배열 크기 5

        ROM biosROM(1024 * 10, x, 5); //10KB ROM 메모리, 배열 x로 초기화됨.

        RAM mainMemory(1024 * 1024); //1MB RAM 메모리

 

                                                              //0번지에서 4번지까지 biosROM에서 읽어 mainMemory에 복사

        for (int i = 0; i < 5; i++) { mainMemory.write(i, biosROM.read(i)); }

        //램 메인메모리에 있는 캐릭터 배열의 i인덱스에 롬 바이오스롬에 들어있는 캐릭터 배열의 i인덱스 원소를 삽입한다.

        for (int i = 0; i < 5; i++) { cout << mainMemory.read(i); } //메인메모리에 있는 캐릭터배열 0~4인덱스 원소를 순회하고 출력한다.

 

        return 0;

}

<결과창>

 


반응형

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

WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
반응형

8.6> BaseArray 클래스를 상속받아 스택으로 작동하는 MyStack 클래스를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

 

class MyStack : public BaseArray{

private:

        int rear; //마지막 인덱스 리어

public:

        MyStack(int capacity,int rear);

        void push(int arg); //마지막에 원소 추가

        int capacity(); //스택 용량

        int length(); //스택 길이

        int pop(); //마지막 원소 꺼내옴

};

MyStack::MyStack(int capacity=100,int rear=-1):BaseArray(capacity) {this->rear=rear;}

void MyStack::push(int arg) {rear++; put(rear,arg);}

int MyStack::capacity() {int cap=getCapacity(); return cap;}

int MyStack::length(){return rear+1;}

int MyStack::pop(){int out=get(rear); rear--; return out;}

 

int main(void){

MyStack mStack(100);

        int n;

        cout << "스택에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mStack.push(n); //큐에 삽입

        }

        cout<<"스택 용량: " <<mStack.capacity()<<", 스택 크기:"<<mStack.length()<<endl;

        cout<<"스택의 모든 원소를 팝하여 출력한다>> ";

        while(mStack.length()!=0){

               cout<<mStack.pop()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mStack.length()<<endl;

        return 0;

}

 

<결과창>

  

 

반응형

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

Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
반응형

8.5> BaseArray를 상속받아 큐처럼 작동하는 MyQueue 클래스를 작성하라. MyQueue를 활용하는 사례는 다음과 같다.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

class MyQueue : public BaseArray{

private:

        int rear; //마지막 인덱스

        int front; // 첫번째 인덱스 -1

public:

        MyQueue(int capacity,int front,int rear); // 생성자

        void enqueue(int arg); //마지막에 원소 추가

        int capacity(); //용량

        int length(); //현재 길이

        int dequeue(); //첫번째 원소 리턴

};

MyQueue::MyQueue(int capacity=100,int front=-1,int rear=-1):BaseArray(capacity){

        this->front=front;

        this->rear=rear;

}

void MyQueue::enqueue(int arg){

        rear++;

        put(rear,arg);

}

int MyQueue::capacity(){int cap=getCapacity(); return cap;}

int MyQueue::length(){

        return rear-front;

}

int MyQueue::dequeue(){

        int out=get(front+1);

        front++;

        return out;

        }

int main(void){

        MyQueue mQ(100);

        int n;

        cout << "큐에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mQ.enqueue(n); //큐에 삽입

        }

        cout<<"큐의 용량: " <<mQ.capacity()<<", 큐의 크기:"<<mQ.length()<<endl;

        cout<<"큐의 원소를 순서대로 제거하여 출력한다>> ";

        while(mQ.length()!=0){

               cout<<mQ.dequeue()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mQ.length()<<endl;

        return 0;

}

 

<결과창>

  

                                 


반응형

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

ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
반응형

6.5> 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility{

public:

        static void intToDouble(int source[], double dest[], int size);

        //int[] double[] 변환

        static void doubleToInt(double source[], int dest[], int size);

        //double[] int[] 변환

};

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(void){

        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); // x[]-> y[]

        for(int i=0;i<5;i++) cout << y[i] << ' ';

        cout << endl;

        ArrayUtility::doubleToInt(z,x,5); //z[]->x[]

        for(int i=0;i<5;i++) cout << x[i] << ' ';

        cout << endl;

        return 0;

}


<결과창>



}


반응형

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

Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
반응형

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

<코드>

#include <iostream>

 

using namespace std;

 

class MyVector{

private:

        int* mem;

        int size;

public:

        MyVector(int n,int val);

        ~MyVector(){delete []mem;} //동적 배열이 할당받은 메모리를 힙에 반환

        void printVector();

};

 

MyVector::MyVector(int n=100,int val=0){

        //n실인자가 입력되지 않으면 100대입,val 실인자 없으면 0대입

        mem=new int[n]; //n크기의 인트형 동적 배열

        size=n;

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

               mem[i]=val; //동적 배열의 모든 원소를 val 초기화해준다.

}

void MyVector::printVector(){ //10개씩 끊어서 출력

        int moc=size/10; //

        int namuji=size%10; //나머지

        for(int j=0;j<moc;j++){

        for(int i=0;i<10;i++){cout<<mem[i];} //몫에 해당하는만큼 출력

        cout<<endl;

        }

        for(int k=0;k<namuji;k++) //나머지에 해당하는 만큼 출력

               {cout<<mem[k];}

        cout<<endl;

}

int main(void){

        MyVector m1; //사이즈 100, 원소는 0

        MyVector m2(53); //사이즈 53, 원소는 0

        MyVector m3(27,3); //사이즈 27, 원소는 3

        m1.printVector();

        m2.printVector();

        m3.printVector();

        return 0;

}

<결과창>

                              

 

반응형

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

배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
반응형

6.2> Person 클래스의 객체를 생성하는 main() 함수는 다음과 같다.

(1) 생성자를 중복 작성하고 프로그램을 완성하라.

<코드1>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person();

        Person(int id, string name);

        Person(int id,string name,double weight); //생성자 오버로딩

};

Person::Person(){//매개변수 없는 생성자

        this->id=1;

        this->weight=20.5;

        this->name="Grace";

}

Person::Person(int id, string name){ //매개변수 2개인 생성자

        this->id=id;

        this->weight=20.5;

        this->name=name;

}

 

Person::Person(int id,string name,double weight){ //매개변수 3개인 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

(2) 디폴트 매개 변수를 가진 하나의 생성자를 작성하고 프로그램을 완성하라.

<코드2>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person(int id,string name,double weight);

};

Person::Person(int id=1,string name="Grace",double weight=20.5){ //디폴트매개변수를 가진 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

        //id 입력이 없으면 1 대입, name 입력이 없으면 "Grace" 대입, weight 입력이 없으면 20.5 대입

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

<결과창>

   

    


반응형

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

동일한 크기의 배열  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
반응형

5.6> 문제 5번의 MyIntStack를 수정하여 다음과 같이 선언하였다. 스택에 저장할 수 있는 정수의 최대 개수는 생성자에서 주어지고 size 멤버에 유지한다. MyIntStack 클래스를 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
 
using namespace std;
 
class MyIntStack{
private:
    int *p; //스택 메모리로 사용할 포인터
    int size//스택의 최대 크기
    int tos; //스택의 탑을 가리키는 인덱스
public:
    MyIntStack();
    MyIntStack(int size);
    MyIntStack(MyIntStack& s);
    ~MyIntStack();
    bool push(int n); //정수 n을 스택에 푸쉬 꽉차있으면 false 아니면 true
    bool pop(int &n);  //스택의 탑에 있는 값을 n에 pop 한다 스택이 비었으면 false 아니면 true
};
MyIntStack::MyIntStack(){size=1;    p=new int[size];    tos=-1;} //기본 생성자 정의 tos=-1은 empty state를 나타낸다.
MyIntStack::MyIntStack(int size){this->size=size;    p=new int[size];    tos=-1;} //인자 size가 동적 배열의 크기를 결정한다.
//tos=-1이 empty 를 뜻하는 이유는 배열의 인덱스가 0부터 시작하기 때문이다.
MyIntStack::MyIntStack(MyIntStack& s){this->size=s.size
    p=new int[s.size]; //깊은 복사를 위해 새로운 동적메모리를 힙에서 size만큼 받아온다.
    for(int i=0;i<s.size;i++){
    (this->p)[i]=(s.p)[i];
    } //포인터에 할당된 동적메모리의 경우 깊은 복사를 위해
//새로운 할당을 해준 후 배열의 원소를 일일히 복사하여 넣어준다.
this->tos=s.tos;}
MyIntStack::~MyIntStack(){
    if(this->p) //p에 주소값이 NULL이 아니면
        delete []p; //p가 가리키는 동적메모리 반환
}
bool MyIntStack::push(int n){
    if((tos+1)==size//index는0부터 시작해서 1을 더해서 검사함
        return false;
    else{
        p[++tos]=n; //증가시키고 대입해준다.
        return true;
    }
}
bool MyIntStack::pop(int &n){
    if(tos==-1//empty면
        return false;
    else{
        n=p[tos--]; //대입하고 감소시킨다.
        return true;
    }
}
int main(void){
    MyIntStack a(10); //size 10짜리 마이인트스택 a
    a.push(10); //a에 10 삽입 pos=0
    a.push(20);//a에 20 삽입 pos=1
    MyIntStack b=a; //MyIntStack b(a); 와 같다.
    //객체로 초기화 하여 객체 생성,복사생성자 실행됨(깊은복사)
    b.push(30); //b에 30 삽입 pos=2
    int n;
    a.pop(n); //20 pop, pos=0이됨
    cout<<"스택 a에서 팝한 값 "<<n<<endl;
    b.pop(n); //30 pop, pos=1이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    b.pop(n); //20 pop, pos=0이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    b.pop(n); //10 pop, pos=-1이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    cout<<b.pop(n)<<endl//pos=-1, empty state 라서 0 리턴
    return 0;
}
 
cs




반응형

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

Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
using namespace std;
 
int main(void){
 
    char c=3;
    int a=1;
    double d=1.0;
 
    char *p1=&c;
    int *p2=&a;
    double *p3=&d;
    cout<<"캐릭터 "<<(int)p1<<" "<<(int)(p1+1)<<endl//1->주소1증가
    cout<<"정수 "<<(int)p2<<" "<<(int)(p2+1)<<endl//1->주소4증가
    cout<<"실수(더블) "<<(int)p3<<" "<<(int)(p3+1)<<endl;//1->주소8증가
}
cs




char 포인터에 더하기 1을 하면 주소는 1이 증가
int 포인터에 더하기 1을 하면 주소는 4이 증가
double 포인터에 더하기 1을 하면 주소는 8이 증가
헷갈리지 말자




반응형

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

Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
using namespace std;
 
int main(void){
 
    int a[2]={6,10};
    int *p=a; //포인터 p는 배열a의 첫번째 원소를 가리키는 포인터
    int &r=*a; //r은 a의 첫번째 원소의 참조
    int &r2=r; //r2는 r의 참조 (참조의 참조)
 
    cout<<a[0]<<endl//6
    cout<<*p<<endl//6
    cout<<r<<endl//6
    cout<<r+1<<endl//6+1=7
    cout<<a<<endl//주소
    cout<<&r<<endl//첫번째 원소의 주소 =a
    cout<<*(&r)<<endl//레퍼런스 주소의 역참조 = 6
    cout<<*(&r+1)<<endl//레퍼런스 주소에 1을 더한것의 역참조 = 10(2번째 원소)
    cout<<r2<<endl//r2는 r을 가리키므로 6
}
cs


포인터는 주소가 담기는 메모리가 할당 된다.

레퍼런스는 메모리 상의 특정 공간을 차지하는 것이 아니라 컴파일 시에

원래 레퍼런스가 참조하던 변수의 *(주소값)으로 대체되는 것이다.







반응형

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

MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
float dorf(float a){return 123;}
double dorf(double a){return 456;}
 
int main(void){
    cout<<dorf(3.0)<<endl;
    cout<<dorf((float)3.0)<<endl;
    cout<<dorf((double)3.0)<<endl;
 
    return 0;
}
cs


함수의 리턴 타입을 float, double로 오버로딩하면

강제 형변환을 하지 않고 실수를 넣었을 때

기본적으로 double이 나온다.

안에 들어간 실수 인자를 double로 자동인식하는 것 같다.




반응형

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

포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
반응형

4.9> 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
 
using namespace std;
 
class Circle{ 
private:
    int radius;
    string name;
public:
    void setCircle(string name, int radius){ //멤버 name과 radius를 set해줌.
        this->name=name; this->radius=radius;
    }
    double getArea(){return radius*radius*3.14;} //원의 면적 리턴
    string getName(){return name;} //원의 이름 리턴
};
 
class CircleManager{
private:
    Circle *p; //Circle형 포인터 p
    int size;
public:
 
    CircleManager(int size){ //컨스트럭터
        this->size=size
        p=new Circle[size]; //size크기만큼의 Circle형 동적 객체 배열 생성
        int radius; string name;
        for(int i=0;i<size;i++){
            cin.ignore(100,'\n'); //cin은 개행문자를 버퍼에 남겨놓기 때문에 버퍼에서 비워줘야 한다.
                                //그렇지 않으면 다음 루프의 getline이 개행문자 + 입력한 문자열을 받아버린다.
            cout<<"원 "<<i+1<<"의 이름과 반지름 >>";
            getline(cin,name,' '); // space를 delimeter로 설정하여 이름을 받는다.
            cin>>radius;     //radius는 cin으로 받는다.
            p[i].setCircle(name,radius); //Circle을 set 해줌.
        }
    cin.ignore(); //마지막 개행문자 버퍼에서 제거
    }
    ~CircleManager(){delete []p;} //동적 Circle 객체 배열 해당 메모리 힙으로 반환
    void searchByName(){
        string cmp;
        cout<<"검색하고자 하는 원의 이름>> ";
        getline(cin,cmp,'\n'); //cmp를 getline으로 개행문자 나올때까지 받는다.
        for(int i=0;i<(this->size);i++){
            if(cmp==(p[i].getName()))  //cmp와 i번째 동적circle의 name이 같으면
            {cout<<"도넛의 면적은 "<<p[i].getArea()<<endl//i번째 동적circle의 area 반환
            break;}
        }
    }
    void searchByArea(){
        int area;
        cout<<"최소 면적을 정수로 입력하세요>> ";
        cin>>area; //area를 받는다.
        cout<<area<<"보다 큰 원을 검색합니다."<<endl;
        for(int i=0;i<(this->size);i++){ //동적 객체 배열 전부 순회하여 area보다 
            if(p[i].getArea()>area) //p번째 circle 객체의 넓이가 크면 출력
                cout<<p[i].getName()<<"의 면적은 "<<p[i].getArea()<<", ";
        }
        cout<<endl//개행 출력
    }
};
 
int main(void){
    int size;
    cout<<"원의 개수 >> " ; 
    cin>>size//원의 개수 정함
    CircleManager m(size); //CircleManager객체 생성
    m.searchByName(); //Name으로 찾기
    m.searchByArea(); //특정 Area 초과인것 찾기
    
    return 0;
}
 
cs




반응형

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

float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
반응형

4.8> 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다. 다음 main()이 작동하도록 Person Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
 
using namespace std;
 
class Person{ //Person 클래스
private:
    string name; 
public:
    Person(string name){this->name=name;} //객체멤버 name을 매개변수 name으로 초기화
    Person(){} //디폴트 생성자
    string getName(){return name;} // 멤버변수 name 리턴
    void setName(string name){this->name=name;} //멤버변수 name set함수
    
};
 
class Family{ //Family 클래스
private:
    Person *p; //Person형 포인터 p
    int size//int형 변수 size
    string Fname; //string 형 객체 Fname
public:
    Family(string name, int size){
        p=new Person[size]; //size 크기만큼 동적 Person 객체 배열 생성
        setFname(name); //Fname을 name으로 초기화
        this->size=size//멤버변수 size를 매개변수 size로 초기화
    }
    string getFname(){return Fname;} //Fname 리턴
    int getSize(){return size;} //size 리턴
    void setFname(string Fname){this->Fname=Fname;} //멤버변수 Fname을 매개변수 Fname으로 셋
    void setName(int num, string name){ 
        p[num].setName(name); //num에 해당하는 인덱스에 존재하는 동적 person 객체 배열 원소의 name 셋
    }
    void show(){
        cout<<getFname()<<"가족은 다음과 같이 "<<getSize()<<"명 입니다."<<endl//size 리턴받아 출력
        for(int i=0;i<size;i++){  //i가 0에서부터 size보다 작을때까지
            cout<<p[i].getName()<<"\t"//동적 person 객체 배열 원소에서 getName멤버 함수 호출하여 출력후 탭문자 출력
        }
        cout<<endl// 한줄 내리기
    }
    ~Family(){delete []p;} //소멸자는 동적person배열에 할당된 메모리를 힙에 반납한다. 
};
 
int main(void){
    Family *simpson = new Family("Simpson"3);  //Fname "Simpson", size 3으로 초기화된 Family형 동적 객체, 그걸 가리키는 포인터 simpson
    simpson->setName(0"Mr. Simpson"); //simpson이가리키는 객체 안에서원소3개의 person형 동적 객체 배열이 생성되었고 그중 0번 원소 초기화
    simpson->setName(1"Mrs. Simpson"); //1번 원소 초기화
    simpson->setName(2"Bart Simpson"); //2번 원소 초기화
    simpson->show(); //출력 함수
    delete simpson; //동적 메모리 힙으로 반환
}
 
cs



반응형

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

히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
반응형

4.6> 실습 문제 5의 문제를 수정해보자. 사용자로부터 다음과 같이 원의 개수를 입력받고, 원의 개수만큼 반지름을 입력받는 방식으로 수정하라. 원의 개수에 따라 동적으로 배열을 할당받아야 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
 
using namespace std;
 
class Circle{ //Circle 클래스
private:
    int radius; //private 타입 인티저 radius
public:
    void setRadius(int radius);
    double getArea();
};
void Circle::setRadius(int radius){  //radius 셋하는 함수
    this->radius=radius; //this->radius는 클래스의 멤버 변수,radius는 멤버 함수의 매개 변수
}
double Circle::getArea(){ //넓이를 구해주는 멤버 함수 getArea
    return radius*radius*3.14;
}
 
int main(void){
    int n=0// 원의 개수
    int count=0//면적이 100보다 큰 원 개수
    int r; //반지름을 담을 변수
    while(true){ //원의 개수를 1보다 작게 했을 때 생기는 오류를 없애주는 무한루프
    cout<<"원의 개수 >> ";
    cin>>n; //n을 받는다.
        if(n>=1//n이 1보다 크면 무한루프 탈출
            break;
    }
    Circle *p=new Circle[n]; //Circle 객체를 동적으로 n개 생성 해당포인터 p
    for(int i=0;i<n;i++){
        cout<<"원 "<<i+1<<"의 반지름 >> "
        cin>>r;
        p[i].setRadius(r); //p[i]의 radius를 r로 설정해준다
        if(p[i].getArea()>100//p[i]의 넓이가 100보다크면
            count++//카운트를 늘려준다.
    }
    cout<<"면적이 100보다 큰 원은 "<<count<<"개 입니다."<<endl//100보다큰원 출력
    delete []p; //동적 배열 메모리 힙에 반환
}
 
cs




반응형
반응형

4.3> string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 입력받고 글자 하나만 랜덤하게 수정하여 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdlib> //random 사용 위함
#include <ctime> //srand 사용 위함
#include <string> //string 객체 사용 위함
 
using namespace std;
 
int main(void){
    string s; //string 객체 s
    srand((unsigned)time(0)); //시드값 설정
    
    cout<<"아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)"<<'\n';
    while(true){ //무한루프
    cout<<">>";
    getline(cin,s,'\n'); //delimeter '\n'으로 한 줄 받아 s에 저장
    if(s=="exit"//s가 exit면 루프 탈출
        break;
    int rand_index=(rand())%(s.length()); //rand_index에 임의 인덱스 저장(s.length로 나눈 나머지는 무조건 0~length-1이 나옴)
    //조심해야 할것은 알파벳만 인덱스에 포함되는 것이 아니라 공백문자, 마침표와 같은 문자도 포함된다.
    int Daeso=rand()%2//글자를 바꾸는데 소문자로 바꿀 것인지 대문자로 바꿀 것인지 랜덤으로 정한다.
    if(Daeso==0//대문자로 정해짐
    s[rand_index]=(char)((rand()%26)+65); //아스키코드 65~90 대문자 알파벳
    else if(Daeso==1//소문자로 정해짐
    s[rand_index]=(char)((rand()%26)+97); //아스키코드 97~122 소문자 알파벳
    cout<<s<<endl//s출력
    }
    return 0;
}
 
cs



반응형

+ Recent posts