2016-11-16 159 views
-3

我給出了以下問題,並要求使用python爲它編寫解決方案算法。用我的代碼遇到一些邏輯錯誤

問題: 編寫一個Python程序來確定平均得分最高的學生。每個學生都需要一箇中期和一個決賽。等級應該在0到100之間進行驗證。輸入每個學生的姓名和成績,並計算學生的平均成績。輸出具有最佳平均值和平均值的學生姓名。

這裏是我的代碼:

def midTerm(): 
    midtermScore = int(input("What is the midterm Score: ")) 
    while (midtermScore <= 0 or midtermScore >= 100): 
     midtermScore = int(input("Please enter a number between 0 and 100: ")) 
    return midtermScore 
def final(): 
    finalScore = int(input("What is the final Score: ")) 
    while (finalScore < 0 or finalScore > 100): 
     finalScore = int(input("Please enter a number between 0 and 100: ")) 
    return finalScore 

total = 0 
highest = 0 
numStudents = int (input("How Many Students are there? ")) 
while numStudents < 0 or numStudents > 100: 
    numStudents = int (input("Please enter a number between 0 and 100? ")) 
for i in range (1, numStudents+1): 
    students = (input("Enter Student's Name Please: ")) 
    score = (midTerm()+ final()) 
    total += score 
avg = total/numStudents 
if (highest < avg): 
    highest = avg 
    winner = students 
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", avg) 

我遇到的問題是最後一部分。該程序不會打印出平均值最高的人的姓名,而是最後輸入的人的姓名。我對如何從這裏前進感到困惑。你能幫忙嗎?預先感謝您的幫助。

+2

看看下面這行:'students =(input(「Enter Student's Name Please:」))' - 你每次都通過循環重新分配它。 'numStudents'也具有相同的分配問題。這對於學習[debug python](https://pymotw.com/2/pdb/)來說也是一個很好的時間,因爲從一眼就可以看出有多個邏輯錯誤,最終會給你提供不正確的結果。 – birryree

+1

你指定'贏家=學生',所以看看學生的價值,它被分配'學生=(輸入(「輸入學生姓名請:」))''你從來沒有真正分配正確的學生導致邏輯錯誤。 – kyle

+0

這裏可能有一個很好的問題,但你的問題標題是不恰當的。請查看http://stackoverflow.com/help/how-to-ask。 –

回答

1

你並不遙遠。看看這裏:

for i in range (1, numStudents+1): 
    students = (input("Enter Student's Name Please: ")) 
    score = (midTerm()+ final()) 
    total += score 
avg = total/numStudents 
if (highest < avg): 
    highest = avg 
    winner = students 

除了縮進錯誤(希望只是笨拙的複製粘貼)你不是實際計算每個學生的平均成績的任何地方。試試這樣的:

for i in range (numStudents): 
    student_name = (input("Enter Student's Name Please: ")) 
    student_avg = (midTerm() + final())/2 # 2 scores, summed and divided by 2 is their average score 
    if (highest < student_avg): 
     highest = student_avg 
     winner = student_name # save student name for later 

print ("The Student with the higgest average is: ", winner, "With the highest average of: ", highest) 

它看起來像你最初試圖計算總的班級平均,這是不是問題陳述所描述的。希望這可以幫助!

+0

非常感謝您花時間幫助解決問題。在發佈之前,我盡力自己回答這個問題,但我在這裏沒有選擇。當然,我是一個python noob,我仍然在學習。你的回答比上面的一些評論要好得多(實際上上面的評論不鼓勵人們提問)。再次感謝! – Doug

+1

可以肯定的是,我認爲熱心的投票是有點苛刻,但是SO確實有堅持的標準。我們都是新手一次,國際海事組織一個模糊標題的體面的問題仍然是一個體面的問題。無論如何,歡迎來到SO! – Will