簡體   English   中英

運行以下代碼時出現邏輯錯誤

[英]Getting a logical error while running following code

from decimal import Decimal
n = int(input())
student_marks = {}
for _ in range(n):
    name, *line = input().split()
    scores = list(map(float, line))
    student_marks[name] = scores
query_name = input()
avg = Decimal(sum(scores)/3)
avg = round(avg, 2)
print(avg)

輸入:

2
Harsh 25 26.5 28
Anurag 26 28 30
Harsh

預計 Output

26.50

我的 Output

28.00

提供的代碼存根將在包含名稱鍵/值對的字典中讀取:[marks] 以獲取學生列表。 打印所提供學生姓名的分數數組的平均值,顯示小數點后 2 位。

第一行包含 integer n,學生記錄數。 接下來的 n 行包含學生獲得的姓名和分數,每個值用空格分隔。 最后一行包含 query_name,即要查詢的學生的姓名。

輸入

3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika

我的 Output

56.00

預計 Output

56.00

我的代碼適用於此輸入,但不適用於其他輸入。 你能試着解釋一下為什么嗎?

在您的情況下,您沒有正確使用查詢。 在計算 avg 時,您總是在計算最后一個人的 avg 分數。

avg = Decimal(sum(scores)/3)

正確的方法是這樣的:

avg = Decimal(sum(student_marks[query_name])/3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM