编译原理词法分析器识别c语言浮点数的识别程序的c语言代码
时间: 2023-10-27 15:05:54 浏览: 123
以下是一个简单的C语言代码,用于识别C语言中的浮点数:
```c
#include <stdio.h>
#include <ctype.h>
enum State {
START,
INTEGER,
FRACTION,
EXPONENT,
EXPONENT_SIGN,
EXPONENT_DIGIT,
ACCEPT
};
enum InputCharType {
DOT,
DIGIT,
E,
PLUS_MINUS,
OTHER
};
enum InputCharType get_input_char_type(char c) {
if (c == '.') {
return DOT;
} else if (isdigit(c)) {
return DIGIT;
} else if (c == 'e' || c == 'E') {
return E;
} else if (c == '+' || c == '-') {
return PLUS_MINUS;
} else {
return OTHER;
}
}
enum State transition(enum State state, enum InputCharType input_char_type) {
switch (state) {
case START:
switch (input_char_type) {
case DIGIT:
return INTEGER;
case DOT:
return FRACTION;
default:
return ACCEPT;
}
case INTEGER:
switch (input_char_type) {
case DIGIT:
return INTEGER;
case DOT:
return FRACTION;
case E:
return EXPONENT;
default:
return ACCEPT;
}
case FRACTION:
switch (input_char_type) {
case DIGIT:
return FRACTION;
case E:
return EXPONENT;
default:
return ACCEPT;
}
case EXPONENT:
switch (input_char_type) {
case DIGIT:
return EXPONENT_DIGIT;
case PLUS_MINUS:
return EXPONENT_SIGN;
default:
return ACCEPT;
}
case EXPONENT_SIGN:
switch (input_char_type) {
case DIGIT:
return EXPONENT_DIGIT;
default:
return ACCEPT;
}
case EXPONENT_DIGIT:
switch (input_char_type) {
case DIGIT:
return EXPONENT_DIGIT;
default:
return ACCEPT;
}
default:
return ACCEPT;
}
}
int main() {
char input[256];
fgets(input, sizeof(input), stdin);
enum State state = START;
for (int i = 0; input[i] != '\0'; i++) {
enum InputCharType input_char_type = get_input_char_type(input[i]);
state = transition(state, input_char_type);
if (state == ACCEPT) {
printf("Valid floating point number\n");
return 0;
}
}
printf("Invalid floating point number\n");
return 0;
}
```
该代码将输入的字符串逐个字符处理,并通过状态转移函数进行状态转移。如果最终状态是接受状态,则表示字符串是有效的浮点数。否则,表示字符串不是有效的浮点数。
阅读全文