14.编程实现:假设学生的基本信息包括学号、姓名、3门课程成绩
时间: 2023-12-22 20:49:21 浏览: 74
可以使用Python语言实现该功能,样例代码如下:
```python
class Student:
def __init__(self, student_id, name, score_list):
self.student_id = student_id
self.name = name
self.score_list = score_list
def calculate_average_score(self):
return sum(self.score_list) / len(self.score_list)
# 测试代码
student = Student('001', '张三', [80, 85, 90])
print(student.student_id)
print(student.name)
print(student.score_list)
print(student.calculate_average_score())
```
以上代码定义了一个名为`Student`的类,该类拥有三个属性:学号、姓名和成绩列表。其中,成绩列表包含了该学生的三门课程成绩。类中还包含了一个`calculate_average_score`方法,用于计算该学生的平均成绩。测试代码创建了一个`Student`对象,并输出了其学号、姓名、成绩列表和平均成绩。
相关问题
已知链表节点信息为学号、姓名、课程成绩。现有两个链表分别包含三个节点。编程实现两个链表的合并然后输出。
假设每个节点都是一个 struct 类型,包含三个字段:`int id 表示学号,`string name` 表示姓名,`double score` 表示课程成绩。现在有两个链表分别为 `list1` 和 `list2`,我们需要将它们合并成一个新的链表 `mergedList`,然后输出所有节点的信息。可以按照以下步骤实现。
1. 定义一个新的链表 `mergedList`,并将其初始化为空链表。
2. 遍历 `list1`,将其中的每个节点插入到 `mergedList` 的尾部。
3. 遍历 `list2`,将其中的每个节点插入到 `mergedList` 的尾部。
4. 遍历 `mergedList`,输出其中每个节点的信息。
下面是具体的实现代码(假设 `Node` 是链表节点的结构体):
```c++
#include <iostream>
#include <string>
#include <list>
using namespace std;
struct Node {
int id;
string name;
double score;
};
int main() {
list<Node> list1 = {{1, "Tom", 80}, {2, "Jerry", 90}, {3, "Alice", 85}};
list<Node> list2 = {{4, "Bob", 95}, {5, "Mike", 92}, {6, "Lucy", 88}};
list<Node> mergedList;
// 将 list1 中的节点插入到 mergedList 的尾部
for (auto it = list1.begin(); it != list1.end(); ++it) {
mergedList.push_back(*it);
}
// 将 list2 中的节点插入到 mergedList 的尾部
for (auto it = list2.begin(); it != list2.end(); ++it) {
mergedList.push_back(*it);
}
// 输出 mergedList 中所有节点的信息
for (auto it = mergedList.begin(); it != mergedList.end(); ++it) {
cout << "id: " << it->id << ", name: " << it->name << ", score: " << it->score << endl;
}
return 0;
}
```
输出结果如下:
```
id: 1, name: Tom, score: 80
id: 2, name: Jerry, score: 90
id: 3, name: Alice, score: 85
id: 4, name: Bob, score: 95
id: 5, name: Mike, score: 92
id: 6, name: Lucy, score: 88
```
. 文件score.txt中存储了若干学生的姓名、学号和3门考试课的成绩。编程,将所有两门以上(含两门)课程不及格的学生信息输出到文件bad.txt、其他学生信息输出到pass.txt。假设score.txt、bad.txt、pass.txt均保存在.py文件的同名目录下。
好的,以下是Python实现代码:
```python
with open('score.txt', 'r') as f:
lines = f.readlines() # 读取所有行
with open('bad.txt', 'w') as f1, open('pass.txt', 'w') as f2:
for line in lines:
name, id, score1, score2, score3 = line.strip().split() # 去掉首尾空格并分割出各字段
# 判断是否两门以上课程不及格
if score1 < '60' and score2 < '60' or score1 < '60' and score3 < '60' or score2 < '60' and score3 < '60':
f1.write(line)
else:
f2.write(line)
```
代码说明:
1. 首先使用`with open()`语句打开score.txt文件,并使用`readlines()`方法读取所有行,存储在列表`lines`中。
2. 接着使用`with open()`语句分别打开bad.txt和pass.txt文件,使用`write()`方法将不及格学生信息写入bad.txt,其他学生信息写入pass.txt。
3. 在循环过程中,使用`strip()`方法去掉每行的首尾空格,使用`split()`方法分割出姓名、学号和3门考试课的成绩。
4. 判断是否两门以上课程不及格,如果是则将该行信息写入bad.txt,否则写入pass.txt。