下面是我用来说明我的问题的示例代码。如果输入是整数或小数,则按预期工作。但是,如果输入是一个分数,例如4/5,它会抛出一个ValueError,因为4/5是一个无法转换为浮点的字符串
myinput=input("Enter number. ")
doubleofmyinput=float(myinput)*2
print(doubleofmyinput)
当不使用input()
时,这不是问题,因为float(4/5)有效,而float(“4/5”)无效,而float(“4.5”)和float(4.5)都有效。谢谢
Tags:
使用fractions library可以执行以下操作:
你希望在接受意见方面有多慷慨
如果它只是普通分数(或混合分数),您可以有一个特殊情况,使用} 或a^{} (取决于您需要或可以容忍的舍入行为).
.split('/')
或正则表达式将输入字符串分解为其组成部分,分别转换,然后将它们组合成float
、a^{如果您想更普遍地接受任意表达式,最好找一个库来实现这一点;一个快速的谷歌建议simpleeval,但可能还有其他的
如果您只想将值作为分数输入,而不将其显示为分数,那么我建议使用eval
相关问题 更多 >
编程相关推荐