大佬咋做啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
你得说清楚每个宿舍是否都是4个人,随机有没有限定条件
如果没有,无非rand()%50就可以了,如果某个宿舍四个人满了,就rand()%49,直到填满
#define NumStu 200
struct Info { //set struct for student
char Names[16];
char Gender[4];
long int No;
int Room;
}Student[NumStu];
struct Buildings { //set struct for buildings
int BNo;
int RNo;
}Building[2];
void main() {
int count, Num[200], NumIndex[50] = {0}, i, j = 0;
srand((unsigned)time(NULL));
while(j < 200){
count = rand() % 50 + 1;
if(NumIndex[count - 1] == 4) continue; // every four students are settled in one room
Num[j] = count;
NumIndex[count - 1]++;
j++;
}
for(i = 0; i < 200; i++){
if(Num[i] <= 25){
if (Num[i] % 5 != 0) Student[i].Room = 1000 + ((Num[i] + 5) / 5) * 100 + Num[i] % 5;
else Student[i].Room = 1000 + (Num[i] / 5) * 100 + 5;
}
else{
Num[i] -= 25;
if (Num[i] % 5 != 0) Student[i].Room = 2000 + ((Num[i] + 5) / 5) * 100 + Num[i] % 5;
else Student[i].Room = 2000 + (Num[i] / 5) * 100 + 5;
}
}
}
不复杂的吧,首先200个学生编上号同时加一个标识,用于标识是否已经分宿舍,用数组存储,然后用一个随机数产生函数,rand() % 200;作为数组下表;放到room的结构体里。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct student {
int no;
int assigned;
}stu[200];
struct room {
int stu_no[4];
int room_no;
}docu[40];
int main(void)
{
int i, j, k, idx;
for (i = 0; i < 200; i++)
stu[i].no = i+1;
for (i = 0; i < 40; i++)
docu[i].room_no = i+1;
srand(time(NULL));
j = k = 0;
for (i = 0; i < 200;) {
idx = rand() % 200;
if (stu[idx].assigned)
continue;
if (j < 4 && docu[k].stu_no[j] == 0) {
docu[k].stu_no[j] = stu[idx].no;
j++;
} else {
j = 0;
k++;
docu[k].stu_no[j++] = stu[idx].no;
}
stu[idx].assigned = 1;
i++;
}
for (i = 0; i < 40; i++)
printf("RoomNo.%d: %d, %d, %d, %d\n", docu[i].room_no,
docu[i].stu_no[0], docu[i].stu_no[1],
docu[i].stu_no[2], docu[i].stu_no[3]);
return 0;
}
供参考,楼主可以改一下,把数字用宏定义一下,这样移植性更好一些
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632