【问题标题】:Arithmetic operation on arrays in Python [duplicate]Python中数组的算术运算[重复]
【发布时间】:2021-10-18 07:41:13
【问题描述】:

在对数组执行算术运算时,输出为整数,为什么输出显示 1. 或 11. 而不是 1.0 或 11.0?有没有办法用浮点值代替 1. 或 11. 将整数显示为 1.0 或 11.0?

【问题讨论】:

  • 也许你可以int(...)结果

标签: python arrays


【解决方案1】:

将其转换为浮动

my_list = [1,2,3,4,5,6]
for element in my_list:
    print( float(element) )

你会得到“1.0”“2.0”和e.t.c

你可以在任何整数上做到这一点

【讨论】:

    【解决方案2】:

    在 Python 中,您可以将浮点数格式化为特定的小数位,如下所示:

    pi = 3.1415926
    formatter = "{0:.2f}"
    output = formatter.format(pi)  # 3.14
    

    您可以在此处阅读更多信息:https://mkaz.blog/code/python-string-format-cookbook/

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多