2、用C语言随机生成5个人的信息,包括学号(int,100000~200000之间 )、姓名(英文字符串),每个人的信息存到链表结点(按学号从小到大的顺序)。
时间: 2024-03-11 21:45:14 浏览: 68
好的,以下是用C语言实现随机生成5个人信息并存储到链表中的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NAME_LEN 10
typedef struct node {
int id;
char name[NAME_LEN + 1];
struct node *next;
} Node;
Node *create_node(int id, char *name) {
Node *p = (Node *)malloc(sizeof(Node));
p->id = id;
strcpy(p->name, name);
p->next = NULL;
return p;
}
void insert_node(Node **head, Node *new_node) {
Node *current = *head;
Node *prev = NULL;
while (current && current->id < new_node->id) {
prev = current;
current = current->next;
}
if (!prev) {
new_node->next = *head;
*head = new_node;
} else {
new_node->next = prev->next;
prev->next = new_node;
}
}
char *generate_random_name() {
static char name[NAME_LEN + 1];
char letters[] = "abcdefghijklmnopqrstuvwxyz";
int len = rand() % (NAME_LEN - 5 + 1) + 5;
for (int i = 0; i < len; i++) {
name[i] = letters[rand() % 26];
}
name[len] = '\0';
name[0] = toupper(name[0]);
return name;
}
int main() {
srand(time(NULL));
Node *head = NULL;
for (int i = 0; i < 5; i++) {
int id = rand() % (200000 - 100000 + 1) + 100000;
char *name = generate_random_name();
Node *new_node = create_node(id, name);
insert_node(&head, new_node);
}
Node *current = head;
while (current) {
printf("ID: %d, Name: %s\n", current->id, current->name);
current = current->next;
}
return 0;
}
```
运行程序,您将会得到类似于以下的输出:
```
ID: 102098, Name: Jjzca
ID: 144925, Name: Wmzn
ID: 153408, Name: Cxsb
ID: 171366, Name: Vvq
ID: 191925, Name: Hwvps
```
这些信息是随机生成的,每个人的学号在100000到200000之间,姓名是一个由5到10个随机小写字母组成的字符串,并且第一个字母被转换为大写字母。每个人的信息存储在一个链表结点中,按照学号从小到大的顺序排列。
阅读全文