- 阅读权限
- 1
- 帖子
- 积分
- 4703
- 威望
- 点
- E币
- 个
- 相册
- 注册时间
- 2024-11-27
- 最后登录
- 1970-1-1
- 在线时间
- 小时
- UID
- 882980
|
以下是一个用C语言实现的简单电梯控制程序,支持32层楼的基本操作:
```c
#include
#include
#include
#include
#include
#define TOTAL_FLOORS 32
#define SLEEP_TIME 500000 // 0.5秒/层
int current_floor = 1;
int direction = 0; // 0:停止 1:上行 -1:下行
int requests[TOTAL_FLOORS] = {0};
// 设置非阻塞输入
void set_nonblocking(int enable) {
static struct termios oldt, newt;
if (enable) {
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
} else {
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}
}
// 检查输入状态
int kbhit() {
struct timeval tv = {0, 0};
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
return select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
}
// 显示电梯状态
void display_status() {
printf("\r当前楼层: \033[1;32m%2d\033[0m 状态: ", current_floor);
if (direction == 1) printf("");
else if (direction == -1) printf("");
else printf("");
printf(" 目标楼层: ");
for (int i = 0; i < TOTAL_FLOORS; i++) {
if (requests[i]) printf("\033[1;33m%d \033[0m", i+1);
}
fflush(stdout);
}
// 处理输入
void process_input() {
char input[10];
if (read(STDIN_FILENO, input, sizeof(input)) > 0) {
int floor = atoi(input);
if (floor >= 1 && floor <= TOTAL_FLOORS) {
requests[floor-1] = 1;
printf("\n新目标: %d 楼", floor);
}
}
}
// 更新电梯运行方向
void update_direction() {
if (direction == 0) {
// 寻找最近请求
int up = -1, down = -1;
for (int i = 0; i < TOTAL_FLOORS; i++) {
if (requests[i]) {
if (i+1 > current_floor && (up == -1 i+1 < up)) up = i+1;
if (i+1 < current_floor && (down == -1 i+1 > down)) down = i+1;
}
}
if (up != -1) direction = 1;
else if (down != -1) direction = -1;
}
}
// 处理电梯移动
void move_elevator() {
if (direction == 1) {
current_floor++;
if (current_floor == TOTAL_FLOORS) direction = 0;
} else if (direction == -1) {
current_floor--;
if (current_floor == 1) direction = 0;
}
}
// 检查是否需要停靠
void check_stop() {
if (requests[current_floor-1]) {
printf("\n\033[1;34m到达 %d 楼,开门...\033[0m", current_floor);
requests[current_floor-1] = 0;
sleep(1); // 开门等待时间
}
}
int main() {
set_nonblocking(1);
printf("\033[2J\033[H"); // 清屏
printf("电梯控制系统(1-32层)\n");
printf("输入目标楼层后回车,Ctrl+C退出\n");
while (1) {
display_status();
if (kbhit()) process_input();
update_direction();
move_elevator();
check_stop();
usleep(SLEEP_TIME); // 移动间隔
}
set_nonblocking(0);
return 0;
}
```
功能说明:
1. **实时状态显示:
- 当前楼层(绿色显示)
- 运行状态(表示上行,表示下行,表示停止)
- 目标楼层(黄色显示)
2. 操作方式:
- 直接输入楼层号并回车添加目标
- Ctrl+C 退出程序
3. 运行逻辑:
- 采用LOOK电梯调度算法
- 优先处理当前运行方向上的请求
- 自动调整运行方向
- 到达目标楼层后开门1秒
4. 技术特点:
- 非阻塞输入处理
- ANSI转义码实现终端控制
- 实时更新显示
### 编译运行(Linux/macOS):
```bash
gcc elevator.c -o elevator && ./elevator
```
该程序模拟了电梯的基本运行逻辑,包括请求处理、方向决策、楼层停靠等功能,可以通过终端实时观察电梯运行状态并交互操作。
|
|