电梯调度算法C语言实现
时间: 2023-08-20 12:38:12 浏览: 83
以下是一个简单的电梯调度算法的C语言实现,仅供参考:
```c
#include <stdio.h>
#define MAX 10 // 电梯最大承载量
#define FLOORS 20 // 楼层数
int floors[FLOORS] = {0}; // 记录每层楼的乘客数
int direction = 1; // 记录电梯的运行方向,1表示上行,-1表示下行
int current_floor = 0; // 记录电梯当前所在楼层
int passengers = 0; // 记录电梯内的乘客数
// 电梯上行
void go_up() {
// 如果电梯到达顶层,改变运行方向
if (current_floor == FLOORS - 1) {
direction = -1;
return;
}
// 否则到达下一层楼
current_floor++;
// 如果有乘客需要在该楼层上行,让他们上电梯
while (floors[current_floor] > 0 && passengers < MAX) {
floors[current_floor]--;
passengers++;
}
}
// 电梯下行
void go_down() {
// 如果电梯到达底层,改变运行方向
if (current_floor == 0) {
direction = 1;
return;
}
// 否则到达下一层楼
current_floor--;
// 如果有乘客需要在该楼层下行,让他们上电梯
while (floors[current_floor] < 0 && passengers < MAX) {
floors[current_floor]++;
passengers++;
}
}
int main() {
int target_floor;
while (1) {
// 模拟电梯的运行
if (direction == 1) {
go_up();
} else {
go_down();
}
// 打印电梯信息
printf("Current floor: %d\n", current_floor);
printf("Passengers: %d\n", passengers);
printf("Direction: %s\n", direction == 1 ? "up" : "down");
// 让乘客输入目标楼层
printf("Please enter the target floor (or -1 to exit): ");
scanf("%d", &target_floor);
// 如果输入-1,退出程序
if (target_floor == -1) {
break;
}
// 如果电梯已满,拒绝新的乘客
if (passengers == MAX) {
printf("The elevator is full. Please wait for the next one.\n");
continue;
}
// 记录乘客的目标楼层
floors[target_floor]++;
}
return 0;
}
```
这个算法模拟了一个简单的电梯调度过程,根据每个乘客的目标楼层,让电梯前往相应的楼层。在达到每个楼层时,如果有需要上行或下行的乘客,就让他们上电梯,直到电梯满员或没有更多的乘客需要上行或下行。