[Python] 분수를 표현하는 방법 (Fraction) ☑️

2022. 10. 22. 13:28·Python

 

from fractions import Fraction
모듈을 import 해 와야 사용할 수 있다.

from fractions import Fraction

print(Fraction(1,3) + Fraction(1,3))
# 2/3

 

 


분수와 정수로 이루어진 수식의 결과는 분수로 나오지만, 소수가 포함된 수식은 결과가 소수로 나온다

from fractions import Fraction

print(Fraction(1,4) + 1)
# 5/4

print(Fraction(1/4) + 1.25)
# 1.5



분자는 .numerator , 분모는 .denominator로 추출한다.

from fractions import Fraction 

print(Fraction(1,3).numerator, Fraction(2,3).denominator)
# 1 3

 

'Python' 카테고리의 다른 글
  • [Python] 배열을 선언하는 방법 ☑️
  • [Python] Collections 모듈 ☑️
  • [Python] int값을 각 자리수로 이루어진 list로 바꾸는 방법 ☑️
  • [Python] 문자열 관련 메서드 ☑️
vysryoo
vysryoo
  • vysryoo
    vysryoo
    vysryoo
  • 전체
    오늘
    어제
    • 분류 전체보기 (129)
      • Python (20)
      • Data structure (12)
      • Algorithm (14)
      • Operating system (18)
      • Programming language theory (12)
      • Computer architecture (6)
      • Softeware engineering (8)
      • Multicore (2)
      • Data Base (3)
      • Problem solving (24)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
vysryoo
[Python] 분수를 표현하는 방법 (Fraction) ☑️
상단으로

티스토리툴바