【问题标题】:How to make python read input as a float?如何使python将输入作为浮点数读取?
【发布时间】:2020-06-07 16:59:54
【问题描述】:

我需要采用以下形式“分数/最大值”(示例 93/100)的输入并将其存储为浮点变量。我遇到的问题是 python 执行反斜杠表示的除法,由于这两个数字是整数,所以结果为 0。即使我将输入转换为浮点数,结果也是 0.0。 这是我的参考代码:

#!/usr/bin/env python

exam1=float(input("Input the first test score in the form score/max:"))

如果输入 93/100,exam1 变量将等于 0.0,而不是预期的 0.93。

【问题讨论】:

  • 请记住,您需要处理“除以零错误”
  • 93/100 不是浮点数。如果您计算其结果,则可以将其解释为浮点数。

标签: python


【解决方案1】:

注意:

input()

从输入中读取一行,将其转换为字符串 (去除尾随的换行符),然后返回。

你可能想试试下面的代码,

string = input("Input the first test score in the form score/max: ")
scores = string.strip().split("/")
exam1 = float(scores[0]) / float(scores[1])

print(exam1)

输入:

Input the first test score in the form score/max: 93/100

输出:

0.93

【讨论】:

  • 您提供的代码不起作用。我得到的错误如下: AttributeError: 'int' object has no attribute 'strip' 如果有帮助,我正在使用 python 2.7。
  • 如果您使用的是 python 2.7,只需将 input 替换为 raw_input
【解决方案2】:

您可以使用 python 的 fractions 模块,它知道如何读取分数字符串

from fractions import Fraction
exam1 = float(Fraction(input("Input the first test score in the form score/max:")))

对于 Python 2.7,使用 raw_input 而不是 input

Python 2.7 getting user input and manipulating as string without quotations

Input the first test score in the form score/max:93/100
>>> exam1
0.93

【讨论】:

猜你喜欢
  • 2016-04-20
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
相关资源
最近更新 更多