为什么python3中的round()内置函数对我不起作用?

时间:2017-12-21 05:24:42

标签: python-3.x rounding built-in

对于给定的学生,我们需要计算平均分数。 输入将是这样的:

3

Krishna 67 68 69

Arjun 70 98 63

Malika 52 56 60

玛莉卡

代码:

if __name__ == '__main__':
n = int(input()) # takes input
student_marks = {} 
for _ in range(n):
    name, *line = input().split()
    scores = list(map(float, line))
    student_marks[name] = scores
query_name = input()

a,b,c=student_marks[query_name]
avg=(a+b+c)/3   #avg is calculated.
output =round(avg,2) ## why can't I use print(round(avg,2)) to give 56.00 but it is giving 56.0 only
print("%.2f" % output) # for my output in two decimal places I had to use this

1 个答案:

答案 0 :(得分:0)

为了得到你所期望的,使用格式函数而不是圆函数。

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

或等效于f-strings(Python 3.6 +):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

与往常一样,浮点值是近似值:

>>> "{}".format(f)
'3.65'
>>> "{:.10f}".format(f)
'3.6500000000'
>>> "{:.20f}".format(f)
'3.64999999999999991118'

对于56

>>> num=56
>>> "The number is {:.2f}".format(num)
'The number is 56.00'