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

问题描述 投票:0回答:1

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

3

克里希纳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
python-3.x rounding built-in
1个回答
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'
© www.soinside.com 2019 - 2024. All rights reserved.