用C语言编写给200个新生随机分配50个宿舍小程序。 (已知楼号,房号;学生学号,班级,性别等信息)
时间: 2023-07-15 09:11:38 浏览: 170
宿舍管理系统(C语言编写的)
3星 · 编辑精心推荐
以下是基于C语言的一个简单实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FLOOR_NUM 5 // 楼层数
#define ROOM_NUM 10 // 每层房间数
#define ROOM_CAPACITY 5 // 房间容纳人数
// 学生信息结构体
typedef struct {
char id[10]; // 学号
char class[10]; // 班级
char gender[10]; // 性别
} StudentInfo;
// 房间信息结构体
typedef struct {
int floor; // 楼层
int room; // 房间号
int cur_capacity; // 当前房间人数
StudentInfo students[ROOM_CAPACITY]; // 学生信息数组
} RoomInfo;
// 初始化房间信息数组
void initRooms(RoomInfo rooms[FLOOR_NUM][ROOM_NUM]) {
for (int i = 0; i < FLOOR_NUM; i++) {
for (int j = 0; j < ROOM_NUM; j++) {
rooms[i][j].floor = i + 1;
rooms[i][j].room = j + 1;
rooms[i][j].cur_capacity = 0;
}
}
}
// 随机分配宿舍
void assignRooms(RoomInfo rooms[FLOOR_NUM][ROOM_NUM], StudentInfo students[], int student_num) {
for (int i = 0; i < student_num; i++) {
int floor, room;
do {
floor = rand() % FLOOR_NUM;
room = rand() % ROOM_NUM;
} while (rooms[floor][room].cur_capacity == ROOM_CAPACITY); // 直到找到空房间
// 将学生信息添加到房间中
rooms[floor][room].students[rooms[floor][room].cur_capacity] = students[i];
rooms[floor][room].cur_capacity++;
}
}
// 输出房间分配结果
void printRooms(RoomInfo rooms[FLOOR_NUM][ROOM_NUM]) {
for (int i = 0; i < FLOOR_NUM; i++) {
printf("第%d层\n", i + 1);
for (int j = 0; j < ROOM_NUM; j++) {
printf("房间%d:", j + 1);
for (int k = 0; k < rooms[i][j].cur_capacity; k++) {
printf("%s ", rooms[i][j].students[k].id);
}
printf("\n");
}
printf("\n");
}
}
int main() {
srand(time(NULL)); // 初始化随机数种子
int student_num = 200;
StudentInfo students[student_num];
for (int i = 0; i < student_num; i++) {
sprintf(students[i].id, "S%03d", i + 1); // 自动生成学号
sprintf(students[i].class, "C%03d", i % 10 + 1); // 自动生成班级
sprintf(students[i].gender, "%s", i % 2 == 0 ? "男" : "女"); // 自动生成性别
}
RoomInfo rooms[FLOOR_NUM][ROOM_NUM];
initRooms(rooms);
assignRooms(rooms, students, student_num);
printRooms(rooms);
return 0;
}
```
这个程序会生成200个学生,随机分配宿舍并输出结果。每个房间最多容纳5人,如果房间已满则会重新随机选择房间。
阅读全文