[내일배움캠프 Day8] C++ 과제 진행

2024. 12. 26. 23:24·내일배움캠프/TIL

 

[1번 과제] CH2 간단한 프로그래밍 구현

#include <iostream>
using namespace std;

// 배열 원소들의 합을 계산하는 함수
int CalSum(int arr[], int size)
{
    int sum = 0;
    for (int i = 0; i < size; i++){
        sum += arr[i];
    }
    return sum;
}

// 배열 원소들의 평균을 계산하는 함수
double CalAvg(int sum, int size)
{
    return static_cast<double>(sum) / size;
}

// 배열을 오름차순으로 정렬하는 함수
void SortAscending(int arr[], int size)
{
    for (int i = 0; i < size - 1; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] > arr[j]) swap(arr[i], arr[j]);
        }
    }
}

// 배열을 내림차순으로 정렬하는 함수
void SortDescending(int arr[], int size)
{
    for (int i = 0; i < size - 1; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] < arr[j]) swap(arr[i], arr[j]);
        }
    }
}

int main()
{
    const int size = 5;
    int num[size];
    int input;
    
    cout << "숫자 입력하기 : ";
    for (int i = 0; i < size; i++)
        cin >> num[i];

    int sum = CalSum(num, size);
    double avg = CalAvg(sum, size);

    cout << "합계 : " << sum << endl;
    cout << "평균 : " << avg << endl;

    cin >> input;
    if (input == 1)
    {
        SortAscending(num, size);
        cout << "오름차순 정렬 결과: ";
    }
    else if (input == 2)
    {
        SortDescending(num, size);
        cout << "내림차순 정렬 결과: ";
    }
    else
        cout << "정렬하지 않은 배열: ";
        
    for (int i = 0; i < size; i++) {
        cout << num[i] << " ";
    }

    return 0;
}

 

 

[2번 과제] CH2 OOP Summary

 

 

Zoo.h

#ifndef ZOO_H
#define ZOO_H
#include "Animal.h"

class Zoo {
private:
    Animal* animals[10]; 
    int animalCount;    

public:
    Zoo();               
    void addAnimal(Animal* animal); 
    void performActions();          
    ~Zoo();            
};

#endif

 

Zoo.cpp

#include "Zoo.h"

// 생성자
Zoo::Zoo() : animalCount(0) {
    for (int i = 0; i < 10; i++) {
        animals[i] = nullptr;
    }
}

// 동물을 동물원에 추가하는 함수
void Zoo::addAnimal(Animal* animal) {
    if (animalCount < 10) {
        animals[animalCount++] = animal;
    }
}

// 동물원에 있는 모든 동물의 울음소리를 출력하는 함수
void Zoo::performActions() {
    for (int i = 0; i < animalCount; i++) {
        if (animals[i]) {
            animals[i]->makeSound();
        }
    }
}

// 소멸자
Zoo::~Zoo() {
    for (int i = 0; i < animalCount; i++) {
        delete animals[i];
    }
}

 

Animal.h

#ifndef ANIMAL_H
#define ANIMAL_H

// 기본 클래스: Animal
class Animal {
public:
    virtual void makeSound() = 0;
    virtual ~Animal() {}
};

// 파생 클래스: Dog
class Dog : public Animal {
public:
    void makeSound() override;
};

// 파생 클래스: Cat
class Cat : public Animal {
public:
    void makeSound() override;
};

// 파생 클래스: Cow
class Cow : public Animal {
public:
    void makeSound() override;
};

#endif

 

Animal.cpp

#include "Animal.h"
#include <iostream>
using namespace std;

void Dog::makeSound() {
    cout << "Dog barks: Woof! Woof!" << endl;
}

void Cat::makeSound() {
    cout << "Cat meows: Meow! Meow!" << endl;
}

void Cow::makeSound() {
    cout << "Cow moos: Moo! Moo!" << endl;
}

 

main.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Zoo.h"

// 랜덤으로 동물 객체를 반환하는 함수
Animal* createRandomAnimal() {
    int random = rand() % 3;
    if (random == 0) return new Dog();
    else if (random == 1) return new Cat();
    else return new Cow();
}

int main() {
    srand(static_cast<unsigned int>(time(0)));
    Zoo myZoo;

    for (int i = 0; i < 5; i++) {
        Animal* animal = createRandomAnimal();
        myZoo.addAnimal(animal);
    }
    myZoo.performActions();

    return 0;
}

 

 

 

'내일배움캠프 > TIL' 카테고리의 다른 글

[내일배움캠프 Day10] 메모리 관리  (0) 2024.12.31
[내일배움캠프 Day9] 포인터  (0) 2024.12.27
[내일배움캠프 Day7] Git  (1) 2024.12.24
[내일배움캠프 Day6] C++ 프로그래밍 기초  (0) 2024.12.23
[내일배움캠프 Day5] 콜리전 수정하기  (3) 2024.12.20
'내일배움캠프/TIL' 카테고리의 다른 글
  • [내일배움캠프 Day10] 메모리 관리
  • [내일배움캠프 Day9] 포인터
  • [내일배움캠프 Day7] Git
  • [내일배움캠프 Day6] C++ 프로그래밍 기초
개발자 밍
개발자 밍
dev0404 님의 블로그 입니다.
  • 개발자 밍
    Developer
    개발자 밍
  • 전체
    오늘
    어제
    • 분류 전체보기 (88)
      • 강의 (8)
        • UE Climbing System (3)
        • UE Dungeon (1)
        • HCI (4)
      • 책 (18)
        • 객체지향의 사실과 오해 (5)
        • Effective C++ (3)
        • 이득우의 게임 수학 (4)
        • 이것이 취업을 위한 컴퓨터 과학이다 (4)
        • 리뷰 (2)
      • C++ (2)
      • 알고리즘 (2)
      • 자료구조 (1)
      • Unreal (4)
      • 내일배움캠프 (52)
        • TIL (52)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    그래픽스
    언리얼
    알고리즘
    게임수학
    컴퓨터구조
    내일배움캠프
    객체지향
    자료구조
    c++
    Effective
    컴퓨터 구조
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
개발자 밍
[내일배움캠프 Day8] C++ 과제 진행
상단으로

티스토리툴바