用C语言写一个三种阶段不同切换的状态机
时间: 2023-11-18 09:06:36 浏览: 35
好的,以下是使用C语言编写一个三种阶段不同切换的状态机的示例代码:
```C
#include <stdio.h>
#include <stdbool.h>
enum states {STATE_1, STATE_2, STATE_3};
enum events {EVENT_1, EVENT_2, EVENT_3};
int main() {
enum states current_state = STATE_1;
while(true) {
// state 1
if(current_state == STATE_1) {
printf("Current state: State 1\n");
// transition to state 2 when event 1 occurs
current_state = (get_event() == EVENT_1) ? STATE_2 : STATE_1;
}
// state 2
else if(current_state == STATE_2) {
printf("Current state: State 2\n");
// transition to state 3 when event 2 occurs
current_state = (get_event() == EVENT_2) ? STATE_3 : STATE_2;
}
// state 3
else if(current_state == STATE_3) {
printf("Current state: State 3\n");
// transition back to state 1 when event 3 occurs
current_state = (get_event() == EVENT_3) ? STATE_1 : STATE_3;
}
}
return 0;
}
// function to simulate events
enum events get_event() {
int event_number;
printf("Enter event number (1-3): ");
scanf("%d", &event_number);
switch(event_number) {
case 1:
return EVENT_1;
case 2:
return EVENT_2;
case 3:
return EVENT_3;
default:
printf("Invalid event number. Please enter 1, 2 or 3.\n");
return get_event();
}
}
```
希望对你有帮助!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)