코딩라이브러리/파이썬

파이썬 소수점 버림 trunc() floor() (with 백준 10869)

유니네 라이브러리 2024. 5. 15. 11:12

소수점 버림 방법에 대해 알아본다.

math.trunc() vs math.floor() 차이점을 알아보고,

소수점 버림 관련 백준 문제 풀이로 연습한다.

 

📌 1. 소수점 버림: trunc()와 floor() 비교

 

파이썬에서 소수점을 버리는 방법에는 math.trunc()math.floor() 두 가지가 있다.

📌 두 함수의 차이점

함수 설명 예시 (x = -2.5)
math.trunc(x) 소수점 이하를 무조건 버림 -2
math.floor(x) 작거나 같은 가장 큰 정수 반환 (음수일 때 더 작은 정수로 내림) -3

 

📌 2. math.trunc() 사용 (소수점 절삭)

 

📌 math.trunc(x)

  • 소수 부분을 제거하고 정수 부분만 남긴다
  • 양수일 때는 floor()와 동일, 음수일 때는 ceil()과 동일하다.
import math

print(math.trunc(2.5))   # 2
print(math.trunc(-2.5))  # -2

 

출력 결과

2
-2

📌 특징:

  • math.trunc(-2.5) → -2 (무조건 버림)

📌 3. math.floor() 사용 (내림 연산)

 

📌 math.floor(x)

  • x보다 작거나 같은 가장 큰 정수를 반환한다.
  • 음수일 때는 더 작은 정수로 내린다.
import math

print(math.floor(2.5))   # 2
print(math.floor(-2.5))  # -3

 

출력 결과

2
-3

📌 특징:

  • math.floor(-2.5) → -3 (더 작은 정수로 내림)

📌 4. 소수점 버림 연습 (백준 10869번 문제 풀이)

 

📌 문제 링크:

🔗 백준 10869번 - 사칙연산

 

🔹 문제 설명

 

두 자연수 A, B가 주어질 때, 다음 연산을 수행하는 프로그램 작성

A + B (덧셈)

A - B (뺄셈)

A * B (곱셈)

A / B (나눗셈 → 소수점 버림)

A % B (나머지)

 

🔹 코드 구현

import math
inpList = input().split(" ")

while True:
    #1 ≤ A, B ≤ 10,000 의 validation check
    if (int(inpList[0]) >= 1 and int(inpList[1]) <= 10000):
        # 덧셈
        plusSum = int(inpList[0]) + int(inpList[1])
        print(plusSum)
        # 뺄셈
        minusSum = int(inpList[0]) - int(inpList[1])
        print(minusSum)
        # 곱셈
        multipSum = int(inpList[0]) * int(inpList[1])
        print(multipSum)
        # x와 y의 정수로 내림한 몫 연산 // 을 사용하지 않고 trunc() 소수점 버림으로 계산
        divSum = int(inpList[0]) / int(inpList[1])
        print(math.trunc(divSum))
        # 나머지
        restSum = int(inpList[0]) % int(inpList[1])
        print(restSum)
        break
    else:
        inpList = input().split(" ")

 

입출력 예시

입력: 7 3
출력:
10
4
21
2
1

📌 특징:

  • A / B의 결과를 math.trunc()로 소수점 버림 처리
  • A % B는 기본적인 나머지 연산 수행

✅ 정리 & 마무리

 

소수점 버림 (math.trunc())

  • 소수점 이하를 무조건 버림
  • 양수 → math.floor(x)와 동일, 음수 → math.ceil(x)와 동일

내림 (math.floor())

  • x보다 작거나 같은 가장 큰 정수 반환
  • 음수일 때 더 작은 정수로 내림 처리

백준 10869번 문제

  • 나눗셈 결과를 math.trunc()로 소수점 제거

📚 파이썬 자습서 참고

 

math — Mathematical functions

This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if...

docs.python.org