Py学习  »  Python

如何在python中简化变量的分数值

Sebastian Przybylski • 5 年前 • 1557 次点击  

我有一个变量叫做 b 谁的价值是这样决定的: b = float(input("What is your y-intercept?")) . 在文件的后面,我想取 (假设它是一个浮点数)并将其转换为如下分数: 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 
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43039
 
1557 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Haresh Singh
Reply   •   1 楼
Haresh Singh    5 年前

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

Daniel Mesejo
Reply   •   2 楼
Daniel Mesejo    5 年前

正如@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 .

steff_bdh
Reply   •   3 楼
steff_bdh    5 年前

为什么 print(Fraction('b')) 不起作用是因为您要求python从字符“b”中创建一部分。你需要做的是得到b的字符串表示,它是str(b),所以 Fraction(str(b))

Prune
Reply   •   4 楼
Prune    5 年前
Fraction(str(b))

这就是如何转换变量的 价值 (而不是它的*名称)到字符串。