[Python] round() 사용시 주의 사항 / 올림, 내림 함수

Suhyeon Lee·2025년 1월 10일
0

자기주도학습

목록 보기
76/83

반올림 함수 round()

  • 파이썬에서 실수를 반올림하고 싶을 때, round() 내장 함수를 사용할 수 있음
    • 내장 함수이기 때문에 별도로 import하지 않음
# round 함수 
print(round(1.5))
print(round(2.5))
print(round(3.5))
print(round(4.5))
print(round(5.5))
  • 위 코드에서 각각의 실수를 반올림하면 2, 3, 4, 5, 6 로 결과값이 예상되지만 실제로 실행한 결과는 아래와 같음

  • 이러한 결과가 나온 이유? 사사오입 원칙 때문!

    • round() 함수는 정수 부분이 홀수일 경우 올림, 짝수일 경우 내림하여 계산함
      (round() 함수를 사용하기 위해서는 해당 사항을 숙지할 것)
  • 간단하게 0.5를 더한 후, 내림 함수(floor)를 사용하면 해결

# math 모듈 import
import math

ex_1 = 1.5
ex_2 = 2.5
ex_3 = 4.5

# 실수에 0.5 를 더하여 내림 (floor) 함수 사용 
print(math.floor(ex_1 + 0.5))
print(math.floor(ex_2 + 0.5))
print(math.floor(ex_3 + 0.5))

올림 함수 ceil()

  • 파이썬 표준 모듈 중 math 를 import 하여, math 모듈의 함수인 ceil() 을 사용할 수 있음
    • math.ceil() 함수는 올림한 값을 리턴함
# math 모듈 import
import math

# math 모듈의 ceil 함수 사용
print(math.ceil(1.1))
print(math.ceil(1.3))
print(math.ceil(1.5))
print(math.ceil(1.7))
print(math.ceil(1.9))

내림 함수 floor()

  • 내림 또한 math 모듈에 내장된 floor 함수를 사용
    • math.floor() 함수는 내림한 값을 리턴
# math 모듈 import
import math

# math 모듈의 floor 함수 사용
print(math.floor(1.1))
print(math.floor(1.3))
print(math.floor(1.5))
print(math.floor(1.7))
print(math.floor(1.9))

profile
2 B R 0 2 B

0개의 댓글

관련 채용 정보