Python - 输出分数而不是小数

时间:2017-02-11 19:51:11

标签: python python-3.x input

所以我试图制作一段计算一条线斜率的代码。我使用的是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)

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

1 个答案:

答案 0 :(得分:3)

是的,请参阅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