【问题标题】:Python - Output fraction instead of decimalPython - 输出分数而不是小数
【发布时间】:2017-02-11 19:51:10
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x input


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多