如何在一组班级平均值中显示最大和最小平均值

时间:2013-02-19 21:03:15

标签: python

我正在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))

1 个答案:

答案 0 :(得分: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))