有人可以解释一下这个状态机程序是如何工作的吗?

标签 c

我无法理解这个程序是如何工作的;有人可以解释一下吗?
我知道它与状态机有关,但我不明白状态机是如何工作的。

void abba();

int main()
{
    printf("Enter 10 characters, a or b.\n");
    abba();

    return 0;
}

void abba() 
{
    int x = 0;
    char  a;

    while ((scanf_s("%c", &a) == 1) && (a == 'a' || a == 'b')) {
        switch (x) {
        case 0:
            if (a == 'a')
                x = 1;
            break;
        case 1:
            if (a == 'b')
                x = 2;
            break;
        case 2:
            if (a == 'b')
                x = 3;
            else
                x = 1;
            break;
        case 3:
            if (a == 'b')
                x = 0;
            else {
                puts("abba is found !");
                x = 4;
            }
            break;
        }
    }
}

最佳答案

这是您的代码的状态机。 enter image description here

如您所见,有 4 个状态。

每个状态的解释

  1. state 0 - If you receives char a you move to state 1 else you stay in the state 0.
  2. state 1 - If you receives char b you move to state 2 else you stay in the state 1.
  3. state 2 - If you receives char b you move to state 3 else you go back to state 1 from there again you need to read bb to reach state 3.
  4. state 3 - If you receives char a you read complete abba else you need to read the input from the beginning.

关于有人可以解释一下这个状态机程序是如何工作的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578569/

相关文章:

C 编译器错误 : unknown type name '__evenaccess'

c - 我如何确定此代码符合哪个 C 标准?

c - 使用 strlen 和函数查找字符串长度。用空字符串打印

c - C中的结构大小

c - 为什么argv[0]的输出不对?

c - 如何在makefile中包含静态库

c++ - collect2.exe : error: ld returned 1 exit status

c++ - 了解类型转换(指针)

c - Fscanf 和字符串

c - 此函数中缺少 free() 导致内存泄漏