有 10 个学生,每个学生的数据包括学号、姓名、3 门课的成绩, 从键盘输入10 个学生的数据,要求打印出 3 门课的总、平均成绩,并计算出每人的平均成绩,将原有 数据和计算出的平均分数存放在磁盘文件
时间: 2023-03-19 09:29:14 浏览: 74
首先,我们需要定义一个学生类,包括学号、姓名和3门课的成绩。然后,从键盘输入10个学生的数据,计算出每门课的总成绩和平均成绩,以及每个学生的平均成绩。最后,将原有数据和计算出的平均分数存放在磁盘文件中。
具体实现步骤如下:
1. 定义学生类,包括学号、姓名和3门课的成绩。
2. 从键盘输入10个学生的数据,存放在一个列表中。
3. 计算每门课的总成绩和平均成绩,以及每个学生的平均成绩。
4. 将原有数据和计算出的平均分数存放在磁盘文件中。
代码示例:
```python
class Student:
def __init__(self, id, name, score1, score2, score3):
self.id = id
self.name = name
self.score1 = score1
self.score2 = score2
self.score3 = score3
def get_total_score(self):
return self.score1 + self.score2 + self.score3
def get_average_score(self):
return self.get_total_score() / 3
students = []
for i in range(10):
id = input("请输入学号:")
name = input("请输入姓名:")
score1 = float(input("请输入第一门课的成绩:"))
score2 = float(input("请输入第二门课的成绩:"))
score3 = float(input("请输入第三门课的成绩:"))
student = Student(id, name, score1, score2, score3)
students.append(student)
score1_total =
score2_total =
score3_total =
for student in students:
score1_total += student.score1
score2_total += student.score2
score3_total += student.score3
score1_average = score1_total / len(students)
score2_average = score2_total / len(students)
score3_average = score3_total / len(students)
with open("students.txt", "w") as f:
for student in students:
average_score = student.get_average_score()
f.write(f"{student.id}\t{student.name}\t{student.score1}\t{student.score2}\t{student.score3}\t{average_score}\n")
f.write(f"平均成绩\t\t{score1_average}\t{score2_average}\t{score3_average}\n")
```
运行程序后,会依次提示输入每个学生的数据,然后会在当前目录下生成一个名为“students.txt”的文件,其中包含每个学生的数据和每门课的平均成绩。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)