Python - 输出分数而不是小数

3 python input python-3.x

所以我正在尝试编写一段代码来计算一条线的斜率。我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

每当我输入使答案变得不合理的数字时,答案就会变成小数。是否可以将其保留为分数?

Kir*_*gin 7

是的,请参阅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))
Run Code Online (Sandbox Code Playgroud)

输入输出:

First y point: 5
Second y point: 7
First X point: 10
Second X point: 15
The slope is: 2/5 = 0.4
Run Code Online (Sandbox Code Playgroud)