【问题标题】:ValueError: could not convert string to float: '8/3'ValueError:无法将字符串转换为浮点数:\'8/3\'
【发布时间】:2022-10-13 17:26:04
【问题描述】:

我有以下说明

x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())

当我尝试以小数值执行它时,例如8/3,我收到一条错误消息。

x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())
0.1 0.2 -8 -16.67 0 0.1 8/3 1
# output
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())
ValueError: could not convert string to float: '8/3'

我在这里做错了什么?提前感谢您的任何帮助。

【问题讨论】:

    标签: python input type-conversion


    【解决方案1】:

    8/3 不是 python 浮点数的有效表示法。但是,您可以使用 fractions 模块解析这些输入:

    >>> import fractions
    >>> inp = '0.1 0.2 8/3 1/2 -5/10'
    >>> [float(fractions.Fraction(s)) for s in inp.split()]
    [0.1, 0.2, 2.6666666666666665, 0.5, -0.5]
    

    【讨论】:

      【解决方案2】:

      字符串8/3 无法使用float 进行转换,只需使用fractions 模块中的内容即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-23
        • 2018-06-13
        • 2013-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-04
        相关资源
        最近更新 更多