面试题答案
一键面试#include <stdio.h>
// 定义枚举类型表示交通信号灯的状态
typedef enum {
RED,
GREEN,
YELLOW
} TrafficLightState;
// 函数声明
TrafficLightState nextState(TrafficLightState currentState);
void printState(TrafficLightState state);
int main() {
TrafficLightState currentState = RED;
printf("初始状态: ");
printState(currentState);
// 模拟状态转换
for (int i = 0; i < 6; i++) {
currentState = nextState(currentState);
printf("转换后的状态: ");
printState(currentState);
}
return 0;
}
TrafficLightState nextState(TrafficLightState currentState) {
switch (currentState) {
case RED:
return GREEN;
case GREEN:
return YELLOW;
case YELLOW:
return RED;
default:
return RED;
}
}
void printState(TrafficLightState state) {
switch (state) {
case RED:
printf("红灯\n");
break;
case GREEN:
printf("绿灯\n");
break;
case YELLOW:
printf("黄灯\n");
break;
}
}
枚举在其中起到的作用:
- 提高代码可读性:使用
RED
、GREEN
、YELLOW
这些有意义的标识符来代表交通信号灯的不同状态,相较于直接使用数字,代码意图更加清晰,易于理解和维护。 - 类型安全:枚举定义了一种新的数据类型
TrafficLightState
,编译器可以确保变量的取值只能是枚举中定义的常量,避免了意外赋值非法状态值的错误,提高了代码的健壮性。