#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_FLOOR 21
#define MAX_CAPACITY 10
int main()
{
srand(time(NULL)); // 初始化随机数种子
int current_floor = 1; // 初始电梯所在楼层为1
int direction = 1; // 初始电梯运行方向为向上
int passenger_count = 0; // 初始电梯内乘客数为0
int waiting_count = 30; // 初始楼下等待电梯的人数为30
int elapsed_time = 0;
while (elapsed_time < 10 * 60) // 模拟10分钟内的电梯运行
{
// 每5秒更新一次电梯状态
if (elapsed_time % 5 == 0)
{
printf("第%d秒,电梯在%d层,向%s运行,已经跨越了%d层,有%d人在等待电梯,电梯内有%d人\n",
elapsed_time, current_floor, direction == 1 ? "上" : "下", direction * (current_floor - 1), waiting_count, passenger_count);
}
// 判断电梯是否到达顶层或底层,需要改变运行方向
if (current_floor == MAX_FLOOR)
{
direction = -1;
}
else if (current_floor == 1)
{
direction = 1;
}
// 电梯内的乘客随机选择目标楼层
for (int i = 0; i < passenger_count; i++)
{
int target_floor = rand() % (MAX_FLOOR - 1) + 2;
if (target_floor > current_floor && direction == 1)
{
current_floor++;
}
else if (target_floor < current_floor && direction == -1)
{
current_floor--;
}
}
// 处理电梯内的乘客到达目标楼层,从电梯中移除
for (int i = 0; i < passenger_count; i++)
{
if (rand() % 100 < 10) // 10%的概率下电梯
{
passenger_count--;
}
}
// 处理等待电梯的乘客进入电梯
int new_passengers = rand() % 3;
for (int i = 0; i < new_passengers; i++)
{
if (passenger_count < MAX_CAPACITY && waiting_count > 0)
{
int target_floor = rand() % (MAX_FLOOR - 1) + 2;
if (target_floor > current_floor && direction == 1)
{
passenger_count++;
waiting_count--;
}
else if (target_floor < current_floor && direction == -1)
{
passenger_count++;
waiting_count--;
}
}
}
// 电梯跨越一层楼需要0.5秒
elapsed_time += 500;
}
return 0;