随机生成n(n<10)个学生的个人信息(包括姓名、学号、性别)及考试成绩(数学、英语.物理、计算机),并用单链表存储数据。
时间: 2023-10-20 08:36:13 浏览: 41
好的,我可以帮你解决这个问题。以下是一个示例程序,可以随机生成n个学生的个人信息和考试成绩,并将它们存储在单链表中。
```c++
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// 定义学生结构体
struct Student {
string name; // 姓名
string id; // 学号
char gender; // 性别
int math; // 数学成绩
int english; // 英语成绩
int physics; // 物理成绩
int computer; // 计算机成绩
Student* next; // 指向下一个节点的指针
};
// 随机生成n个学生的个人信息和考试成绩
void generateStudents(Student* head, int n) {
Student* p = head;
for (int i = 0; i < n; i++) {
// 生成姓名
string name = "";
for (int j = 0; j < 3; j++) {
char c = 'A' + rand() % 26;
name += c;
}
// 生成学号
string id = "";
for (int j = 0; j < 8; j++) {
char c = '0' + rand() % 10;
id += c;
}
// 生成性别
char gender = (rand() % 2 == 0) ? 'M' : 'F';
// 生成成绩
int math = rand() % 101;
int english = rand() % 101;
int physics = rand() % 101;
int computer = rand() % 101;
// 创建新节点
Student* newStudent = new Student;
newStudent->name = name;
newStudent->id = id;
newStudent->gender = gender;
newStudent->math = math;
newStudent->english = english;
newStudent->physics = physics;
newStudent->computer = computer;
newStudent->next = NULL;
// 将新节点插入链表
p->next = newStudent;
p = newStudent;
}
}
// 打印所有学生的个人信息和考试成绩
void printStudents(Student* head) {
Student* p = head->next;
while (p != NULL) {
cout << "Name: " << p->name << endl;
cout << "ID: " << p->id << endl;
cout << "Gender: " << p->gender << endl;
cout << "Math: " << p->math << endl;
cout << "English: " << p->english << endl;
cout << "Physics: " << p->physics << endl;
cout << "Computer: " << p->computer << endl;
cout << endl;
p = p->next;
}
}
int main() {
srand(time(NULL)); // 初始化随机数生成器
int n = rand() % 10; // 随机生成n的值
Student* head = new Student; // 创建头节点
head->next = NULL; // 初始化链表为空
generateStudents(head, n); // 生成学生信息
printStudents(head); // 打印学生信息
return 0;
}
```
上述程序中,我们使用了rand()函数来生成随机数,需要在使用之前调用srand()函数来初始化随机数生成器。同时,我们使用了链表来存储学生信息,其中头节点不存储实际数据。在程序的generateStudents函数中,我们使用循环生成n个学生的信息,并将它们插入到链表中。在printStudents函数中,我们遍历链表并打印每个节点的信息。
相关推荐
![](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)