设计一个程序统计某个班全体学生 3 门课的考试成绩。 要求能输入学生人数,并按编号从小到大的顺序依次输入学生的成绩,再统计出每门课程的全班总分、平均分及每个考生所有考试的总分和平均分。
时间: 2024-10-09 11:05:22 浏览: 34
设计这样一个程序可以分为以下几个步骤:
1. 定义数据结构:创建一个名为`Student`的类,包含属性如姓名、学号(用于唯一标识)、以及一个字典(例如`scores`),用于存储三门课程的成绩。
```python
class Student:
def __init__(self, id):
self.id = id
self.scores = {'math': 0, 'english': 0, 'science': 0}
def add_score(self, subject, score):
self.scores[subject] = score
def total_scores(self):
return sum(self.scores.values())
def average_scores(self):
if len(self.scores) == 0:
return 0
else:
return self.total_scores() / len(self.scores)
```
2. 创建一个`Class`类,用于管理学生列表:
```python
class Class:
def __init__(self):
self.students = []
def add_student(self, student_id):
new_student = Student(student_id)
self.students.append(new_student)
def input_scores(self):
for i in range(len(self.students)):
print(f"请输入学生 {i+1} 的各科成绩:")
for subject in ['math', 'english', 'science']:
score = int(input(f"{subject}: "))
self.students[i].add_score(subject, score)
def calculate_totals(self):
totals = {'math': 0, 'english': 0, 'science': 0}
for student in self.students:
for subject, score in student.scores.items():
totals[subject] += score
return totals, [student.total_scores() for student in self.students]
def calculate_averages(self):
class_totals, individual_totals = self.calculate_totals()
avg_class = {subject: class_totals[subject] / len(self.students) for subject in class_totals}
avg_indiv = [student.average_scores() for student in self.students]
return avg_class, avg_indiv
```
3. 主函数`main`,用于交互式操作:
```python
def main():
num_students = int(input("请输入学生人数: "))
class_instance = Class()
for _ in range(num_students):
class_instance.add_student(_ + 1)
class_instance.input_scores()
class_totals, indiv_totals = class_instance.calculate_totals()
class_averages, indiv_averages = class_instance.calculate_averages()
print("\n班级成绩汇总:")
for subject, total in class_totals.items():
print(f"{subject} 总分: {total}, 平均分: {class_averages[subject]}")
print("\n每位学生成绩汇总及平均分:")
for i, student_id in enumerate(class_instance.students):
print(f"学生{student_id.id}:")
print(f"总分: {indiv_totals[i]}, 平均分: {indiv_averages[i]}")
if __name__ == "__main__":
main()
```
阅读全文