用C语言编写给200个新生随机分配50个宿舍小程序。 (已知楼号,房号;学生学号,班级,性别等信息)
时间: 2023-07-15 11:11:38 浏览: 160
宿舍管理系统(C语言编写的)
3星 · 编辑精心推荐
这是一个简单的随机分配算法,可以参考一下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_OF_DORM 200
#define NUM_OF_STUDENT 10000
#define NUM_OF_ROOM 50
struct student {
int id;
int gender;
int dorm;
};
void assign_dorm(struct student* students, int num_of_student) {
// 初始化宿舍
int dorms[NUM_OF_DORM][NUM_OF_ROOM];
for (int i = 0; i < NUM_OF_DORM; i++) {
for (int j = 0; j < NUM_OF_ROOM; j++) {
dorms[i][j] = 0;
}
}
// 随机分配宿舍
srand((unsigned)time(NULL));
for (int i = 0; i < num_of_student; i++) {
int dorm = rand() % NUM_OF_DORM;
int room = rand() % NUM_OF_ROOM;
while (dorms[dorm][room] != 0) {
dorm = rand() % NUM_OF_DORM;
room = rand() % NUM_OF_ROOM;
}
dorms[dorm][room] = students[i].id;
students[i].dorm = dorm * 100 + room;
}
}
int main() {
struct student students[NUM_OF_STUDENT];
// 初始化学生信息,这里只随机生成了学号和性别
for (int i = 0; i < NUM_OF_STUDENT; i++) {
students[i].id = i + 1;
students[i].gender = rand() % 2;
}
assign_dorm(students, NUM_OF_STUDENT);
// 打印宿舍分配结果
for (int i = 0; i < NUM_OF_DORM; i++) {
printf("Dorm %d:\n", i);
for (int j = 0; j < NUM_OF_ROOM; j++) {
printf("Room %d: ", j);
for (int k = 0; k < NUM_OF_STUDENT; k++) {
if (students[k].dorm == i * 100 + j) {
printf("%d ", students[k].id);
}
}
printf("\n");
}
}
return 0;
}
```
这个程序会生成一个包含 10000 个学生的结构体数组,每个学生包含学号、性别和宿舍号等信息。然后使用随机算法将这 10000 个学生随机分配到 200 个宿舍的 50 个房间中,最后输出宿舍分配结果。
阅读全文