【问题标题】:How to simplify a variable's fraction value in Python如何在 Python 中简化变量的分数值
【发布时间】:2019-09-19 00:05:18
【问题描述】:

我有一个名为b 的变量,其值是这样确定的:b = float(input("What is your y-intercept?"))。在文件的后面,我想取b 的值(假设它是一个浮点数)并将其转换为这样的分数:print(Fraction(b))。我知道像print(Fraction(0.45)) 这样的东西会打印8106479329266893/18014398509481984,但print(Fraction('0.45')) 会打印9/20。如何使用变量获得相同的结果?执行print(Fraction('b')) 会给我这个错误:ValueError: Invalid literal for Fraction: 'b'

代码:

from fractions import Fraction

elif equation == 'slope':    
    slope = input("Do you need to find slope? Type 'yes' or 'no'.")

    if slope == 'yes':
       y2 = float(input("What's your y2 value?:"))
       y1 = float(input("What is your y1 value?"))
       x2 = float(input("What is your x2 value?:"))
       x1 = float(input("What is your x1 value?:"))

        m = y2-y1/x2-x1
        print(str(m))
    elif slope == 'no':
        m = input("What is the slope?")

    b = float(input("What is your y-intercept?"))
    m = str(m)
    b = str(b)
    print("Your equation is: y = {}x + {}".format(m,b))
    simplify = input("Do you want to simplify this to standard form? Type in 'yes' or 'no'")

    if simplify == 'yes':
        m = float(m)
        b = float(b)
        if m < 0:
            pos_m = m*-1
        if isinstance(b, float):
            print(Fraction(b)) #Works, but not what I want
            print(Fraction('b')) #Does not work 

【问题讨论】:

  • 你可以试试Fraction(str(b))

标签: python python-3.x fractions


【解决方案1】:
Fraction(str(b))

这就是你如何将变量的(而不是它的*名称)转换为字符串。

【讨论】:

    【解决方案2】:

    print(Fraction('b')) 不起作用的原因是因为您要求 python 从字符“b”中创建一个分数。您需要做的是获取 b 的字符串表示形式,即 str(b),所以 Fraction(str(b))

    【讨论】:

      【解决方案3】:

      正如@Prune 提到的,您必须将变量的值转换为字符串,一种替代方法是使用f-string

      from fractions import Fraction
      b = 0.45
      print(Fraction(f'{b}'))
      

      建议的文档解决方案是使用limit_denominator:

      b = 0.45
      print(Fraction(b).limit_denominator())
      

      输出

      9/20
      

      有关浮点的更多信息,请参阅this

      【讨论】:

        【解决方案4】:

        为什么要使用浮点变量?最好使用 int() 函数来简单地回答。创建一个整数而不是添加一个小数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-08
          • 1970-01-01
          • 2011-02-25
          • 1970-01-01
          相关资源
          最近更新 更多