2013-02-19 253 views
0

我正在用python編寫一個程序,允許用戶輸入班級中的學生人數,然後爲每個學生輸入3個測試成績。它還需要顯示學生的考試平均分,班級平均分,以及班級中的最高和最低平均分。現在,在每個學生的成績和平均成績打印後,我無法打印出平均成績。我也無法讓最高分和最高分都工作,因爲它隨着每個學生的變化而變化爲該學生的平均水平。如何在一組類平均值中顯示最大和最小平均值

students=int(input('Please enter the number of students in the class: ')) 

for number in range(students): 

    class_average == 0 

    first_grade=int(input("Enter student's first grade: ")) 
    second_grade=int(input("Enter student's second grade: ")) 
    third_grade=int(input("Enter student's third grade: ")) 


    StudentAverage=(first_grade + second_grade + third_grade)/3 
    print("The student's average is", round(StudentAverage,2)) 



    class_average= class_average + StudentAverage 
    print("The class average is", round(class_average/students,2)) 



maximum_num = 0 

if StudentAverage > maximum_num: 
    maximum= StudentAverage 
    print("The maxiumum average is", round(maximum,2)) 


minimum_num = 100 

if StudentAverage < minimum_num: 
    minimum= StudentAverage 
    print("The minimum average is", round(minimum,2)) 
+0

第一部分很簡單 - 只是unindent第一個for循環的最後兩行。 – 2013-02-19 21:08:10

+0

如果我這樣做,它不會給出正確的平均值,但我認爲它給出了最終學生的平均值除以學生人數。 – tinydancer9454 2013-02-19 21:22:18

回答

2

我感動外循環的初始化,因此值不會每次迭代期間復位。我將最大和最小比較移入循環,並替換了最大和最小變量。每個新值分別小於和大於這些值,因此需要使用maximum_num和minimum_num來代替。運行班級平均數過低,因爲它使用的是學生總數而不是當前計算的數字。我用數字+ 1取代了學生的使用。我認爲這是你想要的代碼。

students=int(input('Please enter the number of students in the class: ')) 
class_average = 0 
maximum_num = 0 
minimum_num = 100 
for number in range(students): 

    first_grade=int(input("Enter student's first grade: ")) 
    second_grade=int(input("Enter student's second grade: ")) 
    third_grade=int(input("Enter student's third grade: ")) 

    StudentAverage=(first_grade + second_grade + third_grade)/3 
    print("The student's average is", round(StudentAverage,2)) 

    class_average= class_average + StudentAverage 
    print("The class average is", round(class_average/(number+1),2)) 

    if StudentAverage > maximum_num: 
    maximum_num = StudentAverage 

    if StudentAverage < minimum_num: 
    minimum_num = StudentAverage 
print("The minimum average is", round(minimum_num,2)) 
print("The maxiumum average is", round(maximum_num,2)) 
相關問題