【问题标题】:Formatting results to display two decimal places格式化结果以显示两位小数
【发布时间】:2018-09-20 11:12:09
【问题描述】:

我正在尝试格式化以下程序,以便“平均”的结果仅显示到小数点后 2 位。我知道'%.2f' % 代码用于执行此操作,但我不知道如何将其集成到产生错误的最后一行代码中。

这是我正在开发的程序。

#the user has to enter three numbers for the program to average

#request the first number
answer1 = input('Please enter the first number: ')
answer1 = int(answer1)

#request the second number
answer2 = input('Please enter the second number: ')
answer2 = int(answer2)

#request the third number
answer3 = input('Please enter the third number: ')
answer3 = int(answer3)

final = answer1 + answer2 + answer3
final = int(final)

#print the average
print('The average of these numbers is ', final / 3)

这是最后一行,我不知道在哪里插入 '%.2f' % 以返回小数点后 2 位的结果。

任何帮助将不胜感激。

【问题讨论】:

标签: python number-formatting


【解决方案1】:
print('The average of these numbers is %0.2f' %final / 3)

【讨论】:

    【解决方案2】:

    您需要将变量final 转换为float。例如,作为整数的 final 将导致 10 / 3 = 3,但作为浮点 10.0 / 3 = 3.333333。 然后您可以使用函数round() 将浮点数舍入到一定的小数位数。 示例:

    a = 10.0
    final = round(a/3, 2)
    final is now 3.33 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2017-01-26
      • 2011-01-01
      相关资源
      最近更新 更多