编写一段计算期末四门课总成绩和平均分的代码
时间: 2024-10-08 16:12:35 浏览: 33
北航计算机专业课 代码及期末复习笔记.zip
当然可以,假设我们有一个简单的结构体或类`Course`表示一门课程,包含名称`name`和分数`score`,并且已经有一个数组或列表`courses`存储了四门课程的数据。这里是一个用Python编写的基本示例:
```python
class Course:
def __init__(self, name, score):
self.name = name
self.score = score
def calculate_total_score(courses):
total_score = sum(course.score for course in courses)
return total_score
def calculate_average_score(courses):
total_score = calculate_total_score(courses)
if len(courses) > 0:
average_score = total_score / len(courses)
return round(average_score, 2) # 四舍五入到小数点后两位
else:
return "No courses available"
# 创建四门课程实例
courses = [Course("语文", 85), Course("数学", 92), Course("英语", 88), Course("物理", 95)]
# 计算总成绩和平均分
total = calculate_total_score(courses)
avg = calculate_average_score(courses)
print(f"四门课程总成绩为:{total}")
print(f"平均分为:{avg}")
阅读全文