본문 바로가기
Coding Test/C++ 줍줍

[C++ 줍줍] 올림, 내림, 반올림

by seoyamin 2022. 9. 5.

▷ 문제 상황 1

숫자를 올림, 내림한 결과를 알고 싶다 !

 

▶ 해결 방법 1

ceil( ), floor( ) 메소드를 이용

* 헤더 :  #include <cmath>

 

int c1 = ceil(2.2);    // c1 = 3
int f1 = floor(4.7);   // f1 = 4

 

 


 

 

▷ 문제 상황 2

숫자를 반올림한 결과를 알고 싶다 !

 

 

▶ 해결 방법 2-1

floor( ) 메소드와 0.5 이용

* 헤더 :  #include <cmath>

 

int f1 = floor(4.7 + 0.5);   // f1 = floor(5.2) = 5
int f2 = floor(4.2 + 0.5);   // f2 = floor(4.7) = 4

 

 

▶ 해결 방법 2-2

round( ) 메소드이용

* C++ 11 부터 사용 가능

* 헤더 :  #include <cmath>

 

int c1 = round(2.2);    // c1 = 2
int f1 = round(4.7);    // f1 = 5