【问题标题】:Python how to add "0." in-front of a numberPython如何添加“0”。在数字前面
【发布时间】:2023-03-03 06:40:19
【问题描述】:

我正在开发一个 python 程序,我需要它添加“0”。在用户输入之前。

例如: 用户输入 65 然后程序输出一个浮点数 0.65

【问题讨论】:

  • float('0.' + input())?请注意,您必须在用户输入 invalidinput 的情况下实施错误检查。

标签: python python-3.x


【解决方案1】:
user_input = input('Please enter a number: ')
if not user_input.isdecimal():
    raise TypeError('Not a decimal.')
new_float = float('0.' + user_input)

【讨论】:

    【解决方案2】:
    user_input = int(input("Enter an integer: "))
    digits = len(str(user_input))
    output = user_input / (10 ** digits)
    print(output)
    

    假设您得到一个整数:您必须计算其中的位数,然后除以 10 的位数幂。

    让我分步解释:

    • 你有 65 个
    • 65 有 2 位数字
    • 10 的 2 次方:10^2 = 100
    • 然后我们将 65 除以 100 得到 0.65

    【讨论】:

      【解决方案3】:
      input = 65
      output = float('0.' + str(input))
      print(output)
      

      【讨论】:

      • 我之前试过这个,但它输出为字符串,我需要输出为浮点数
      猜你喜欢
      • 1970-01-01
      • 2015-12-03
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多