2017-02-11 1 views
0

그래서 선의 기울기를 계산하는 코드를 만들려고합니다. 나는 3.6을 사용하고있다.파이썬 - 십진수 대신 분수 출력

y1 = float(input("First y point: ")) 
    y2 = float(input("Second y point: ")) 
    x1 = float(input("First X point: ")) 
    x2 = float(input("Second X point: ")) 

    slope = (y2 - y1)/(x2 - x1) 

    print("The slope is:",slope) 

답변을 비합리적으로 만드는 숫자를 넣을 때마다 그 답은 10 진수가됩니다. 그것을 분수로 유지하는 것이 가능합니까?

답변

1

예, https://docs.python.org/3.6/library/fractions.html 참조 (그러나 분자와 분모이 경우, 예를 들어, 정수에 합리적이어야 함) :

from fractions import Fraction 

y1 = int(input("First y point: ")) 
y2 = int(input("Second y point: ")) 
x1 = int(input("First X point: ")) 
x2 = int(input("Second X point: ")) 

slope = Fraction(y2 - y1, x2 - x1) 

print("The slope is:", slope, "=", float(slope)) 

입력 및 출력 :이 일을

First y point: 5 
Second y point: 7 
First X point: 10 
Second X point: 15 
The slope is: 2/5 = 0.4 
+1

, 감사합니다! –