格式化结果以显示两位小数

时间:2018-09-20 11:12:10

标签: python number-formatting

我正在尝试格式化跟随程序,以便“平均值”的结果仅显示到小数点后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位。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

print('The average of these numbers is %0.2f' %final / 3)

答案 1 :(得分:0)

您需要将变量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