오늘의 목표

  • 아침 코드카타
  • 2-1 자원 관리 강의 숙제
  • 2-2 강의 수강
  • 2-2 강의 복습
  • 2-3 강의 수강

 


 

 

1. 코드카타

<오늘의 문제> 정수 제곱근 판별

 

주어진 long long n의 n이 정수 x의 제곱인지 확인하고 맞으면 x+1, 아니면 -1을 리턴하는 함수.

 

<구상>

내가 구상할 수 있었던 것은 인덱스 i를 차례대로 증가시키면서 i의 제곱이 long long n과 일치하는지 확인해보는 방법 뿐이었다.

 

이 방식으로 구현해본 코드는 다음과 같다.

 

<구현>

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
//#include <math.h>

long long solution(long long n) {
    long long answer = 0;

    for(long long i = 1; i*i <= n; ++i){
        if(i*i == n){
            answer = (i + 1) * (i + 1);
        } else {
            answer = -1;
        }
    }

    return answer;
}

 

 

그러나 <math.h>의 함수를 사용해서 간단하게 작성할 수도 있다.

math.h의 sqrt 함수를 사용하면 어떤 수의 제곱근을 알 수 있다.

 

sqrt() 함수 레퍼런스

https://en.cppreference.com/w/cpp/numeric/math/sqrt

 

std::sqrt, std::sqrtf, std::sqrtl - cppreference.com

(1) float       sqrt ( float num ); double      sqrt ( double num ); long double sqrt ( long double num ); (until C++23) /*floating-point-type*/             sqrt ( /*floating-point-type*/ num ); (since C++23) (constexpr since C++26) float    

en.cppreference.com

 

double이나 long double을 사용하여 n의 제곱근 x를 구하고, 그 제곱근이 정수인지 아닌지 파악한다.

정수라면 (x+1)*(x+1)을 반환하고, 아니라면 정수 제곱근이 없으므로 -1을 반환하면 된다.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
//#include <math.h>

long long solution(long long n) {
    long long answer = 0;
     double num = sqrt(n);
    
     if( num == (int) num ){
         answer = ((num + 1) * (num + 1));
     } else {
         answer = -1;
     }
    
   
    return answer;
}

 

굿!

 

 


 

2. 2-1 자원 관리 단원 숙제

숙제 1

 

메모리 누수 발생 코드 분석하고 보완하기

C++로 구현된 코드를 분석해서 메모리 누수가 우려되는 부분을 확인한 후, 코드를 수정하세요.

 

메모리 누수가 발생하는 코드

 

#include <iostream>
using namespace std;

class MyClass {
private:
    int* ptr;

public:
    // 생성자
    MyClass() {
        ptr = new int(10); // 동적 메모리 할당
        cout << "메모리 할당 완료!" << endl;
    }

    // 소멸자
    ~MyClass() {
      
    }

    void print() const {
        cout << "값: " << *ptr << endl;
    }
};

int main() {
    MyClass obj;
    obj.print();

    // main 함수 종료
    return 0;
}

 

<수정>

 

#include <iostream>
using namespace std;

class MyClass {
private:
    int* ptr;

public:
    // 생성자
    MyClass() {
        ptr = new int(10); // 동적 메모리 할당
        cout << "메모리 할당 완료!" << endl;
    }

    // 소멸자
    ~MyClass() {
      delete(ptr);
    }

    void print() const {
        cout << "값: " << *ptr << endl;
    }
};

int main() {
    MyClass obj;
    obj.print();

    // main 함수 종료
    return 0;
}

 

동적할당한 메모리를 delete() 해주지 않아서 생긴 문제 같아서 소멸자에 추가해줬다.

c++는 free()가 아니라 new-delete를 사용한다.

 

<실행>

메모리 할당 완료!
값: 10

 

실행할 때 티가 나지는 않지만 프로그램을 돌리면 돌릴수록 메모리가 부족해질 것이기 때문에 제때 해제해줘야한다.

 

 

숙제 2

스마트 포인터를 활용한 로그분석기 구현

 

#include <iostream>
#include <string>
using namespace std;

class Logger {
private: 
	int logCount;
public:

	Logger(): logCount(0){}

	void logInfo(string message) {
		cout << "[INFO]: " << message << endl;
		++logCount;
	}

	void logWarning(string message) {
		cout << "[WARNING]: " << message << endl;
		++logCount;
	}

	void logError(string message) {
		cout << "[ERROR]: " << message << endl;
		++logCount;
	}

	void showTotalLogs() {
		cout << "Total logs recorded: " << logCount << endl;
	}

	~Logger() {
		cout << "Logger instance destroyed." << endl;
	}
};

int main() {
	unique_ptr<Logger> l = make_unique<Logger>();
	l.logInfo("System is starting.");
	l.logWarning("Low disk space.");
	l.logError("Unable to connect to the server.");
	l.showTotalLogs();
}

 

 

<출력 결과>

[INFO]: System is starting.
[WARNING]: Low disk space.
[ERROR]: Unable to connect to the server.
Total logs recorded: 3
Logger instance destroyed.

 

3. 2-2 템플릿 강의 수강(완료)

 

4. 2-2 템플릿 복습

https://annadevelop.tistory.com/58/

 

티스토리

좀 아는 블로거들의 유용한 이야기, 티스토리. 블로그, 포트폴리오, 웹사이트까지 티스토리에서 나를 표현해 보세요.

www.tistory.com

(비공개글입니다)

 


 

오늘의 배운 점

함수 오버로딩을 할 때, 타입을 명확하게 인식할 수 없을 경우 컴파일러가 애매모호성 오류를 발생시킨다.

이전에 내가 발생시켜본 적 있는 오류이기 때문에 기억해 두자.

 

1. 타입 변환이 가능한 매개변수로 인해 두 개 이상의 오버로딩된 함수가 호출 후보가 되는 경우

2. 디폴트 매개변수로 인해 함수 호출 형태가 중복되는 경우

3. 매개변수의 타입만 포인터와 배열로 다른 경우

4. 함수의 반환 타입만 다른 경우

 

이 네 가지 경우에 오류가 발생하니 오버로딩 시 조심할 것.

 

더 공부해볼 점

오늘은 이해 안되는 부분은 없었다. 오늘 수업한 알고리즘 기초 수업을 다음에 복습할 것!

'Unreal5 공부 > TIL' 카테고리의 다른 글

2026/03/20 TIL  (0) 2026.03.20
2026/03/19 TIL  (0) 2026.03.19
2026/03/17 TIL  (0) 2026.03.17
2026/03/16 TIL  (0) 2026.03.16
2026/03/13 TIL  (0) 2026.03.13

+ Recent posts