数据结构电梯实验代码c语言
时间: 2023-11-06 20:02:52 浏览: 37
下面是一个以C语言实现的电梯模拟代码。电梯共有10层楼,每层楼有两个按键,上行和下行。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义电梯状态
typedef enum {
IDLE, // 空闲
UP, // 上行
DOWN // 下行
} ElevatorState;
// 初始化电梯
void init(ElevatorState *state, int *currentFloor) {
*state = IDLE;
*currentFloor = 1;
}
// 上行
void goUp(int *currentFloor) {
(*currentFloor)++;
}
// 下行
void goDown(int *currentFloor) {
(*currentFloor)--;
}
int main() {
ElevatorState state;
int currentFloor;
int destinationFloor;
init(&state, ¤tFloor);
printf("请输入目标楼层:");
scanf("%d", &destinationFloor);
if (destinationFloor > currentFloor) {
state = UP;
while (currentFloor < destinationFloor) {
goUp(¤tFloor);
}
}
else if (destinationFloor < currentFloor) {
state = DOWN;
while (currentFloor > destinationFloor) {
goDown(¤tFloor);
}
}
printf("电梯到达目标楼层:%d\n", currentFloor);
return 0;
}
```
以上代码是一个简单的电梯模拟,通过输入目标楼层,电梯会根据当前楼层和目标楼层的关系,选择上行或下行并模拟电梯运行到达目标楼层。代码中使用了枚举类型定义了电梯的状态,以及相应的函数实现电梯的操作逻辑。