2017-02-11 7 views
0

Also ich versuche, ein Stück Code zu machen, der die Steigung einer Linie berechnet. Ich benutze 3.6.Python - Ausgabe Bruch statt Dezimal

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) 

Jedes Mal, wenn ich in Zahlen setzen, die die Antwort irrational machen, kommt die Antwort eine Dezimalzahl zu sein. Ist es möglich, es als Bruchteil zu behalten?

Antwort

1

Ja, siehe https://docs.python.org/3.6/library/fractions.html (aber einen Zähler und einen Nenner sollte in diesem Fall zum Beispiel ganze Zahl rational sein):

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)) 

Eingang und Ausgang:

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

Das funktionierte, danke! –