Flex & GNU Bison 简单四则混合运算
2009-10-20 10:26
267 查看
用 Flex 和 GNU Bison 实现的非常简单的计算器,支持 int 和 double 类型的 +-*/% 运算以及括号 ()
main.l
main.y
Makefile(请把下划线替换为空格)
-----
编译运行
make
./main
-----
(1+4)%(4-1)+5.1
7.1
9-(9-(9-(9-9)))
9
.1
0.1
&
error: unknown character
main.l
%{ #include <math.h> #include "main.tab.h" void yyerror(const char *); %} integer [0-9]+ fraction "."{integer} exponent [eE][+-]?{integer} pointfloat {integer}?{fraction}|{integer}"." exponentfloat ({integer}|{pointfloat})exponent real {pointfloat}|{exponentfloat} %% {integer} {yylval.integer = atoi(yytext); return INTEGER; } {real} {yylval.real = atof(yytext); return REAL; } [-()+*/%/n] {return *yytext; } [ /t] ; . {yyerror("error: unknown character/n"); } %% int yywrap(void) { return 1; }
main.y
%{ #include <math.h> #include <stdio.h> void yyerror(const char *); int yylex(void); %} %union{int integer; double real; }; %token <integer> INTEGER %token <real> REAL %type <integer> iexpr %type <real> rexpr %left UMINUS %left '+' '-' %left '*' '/' '%' %% lines: lines expr '/n' | lines '/n' | ; expr: iexpr {printf("%d/n", $1); } | rexpr {printf("%lg/n", $1); } iexpr: INTEGER | '-' iexpr %prec UMINUS {$$ = -$2; } | iexpr '+' iexpr {$$ = $1 + $3; } | iexpr '-' iexpr {$$ = $1 - $3; } | iexpr '*' iexpr {$$ = $1 * $3; } | iexpr '/' iexpr {$$ = $1 / $3; } | iexpr '%' iexpr {$$ = $1 % $3; } | '(' iexpr ')' {$$ = $2; } ; rexpr: REAL | '-' rexpr %prec UMINUS {$$ = -$2; } | rexpr '+' rexpr {$$ = $1 + $3; } | rexpr '-' rexpr {$$ = $1 - $3; } | rexpr '*' rexpr {$$ = $1 * $3; } | rexpr '/' rexpr {$$ = $1 / $3; } | rexpr '%' rexpr {$$ = fmod($1, $3); } | '(' rexpr ')' {$$ = $2; } | rexpr '+' iexpr {$$ = $1 + $3; } | rexpr '-' iexpr {$$ = $1 - $3; } | rexpr '*' iexpr {$$ = $1 * $3; } | rexpr '/' iexpr {$$ = $1 / $3; } | rexpr '%' iexpr {$$ = fmod($1, $3); } | iexpr '+' rexpr {$$ = $1 + $3; } | iexpr '-' rexpr {$$ = $1 - $3; } | iexpr '*' rexpr {$$ = $1 * $3; } | iexpr '/' rexpr {$$ = $1 / $3; } | iexpr '%' rexpr {$$ = fmod($1, $3); } %% void yyerror(const char *s) { fputs(s, stdout); } int main(void) { yyparse(); return 0; }
Makefile(请把下划线替换为空格)
CC = gcc CCFLAGS = -lm RM = rm -f BIN = main OBJS = lex.yy.o $(BIN).tab.o $(BIN): $(OBJS) ${CC} -o $(BIN) $(CCFLAGS) $(OBJS) $(BIN).tab.h $(BIN).tab.c: $(BIN).y bison -d $(BIN).y lex.yy.c: $(BIN).l $(BIN).tab.h flex $(BIN).l .PHONY: clean clean: $(RM) $(OBJS) $(BIN) *.c *.h
-----
编译运行
make
./main
-----
(1+4)%(4-1)+5.1
7.1
9-(9-(9-(9-9)))
9
.1
0.1
&
error: unknown character
相关文章推荐
- JAVA实现简单四则混合运算
- 利用栈ADT写了一个简单的四则混合运算
- JAVA实现简单四则混合运算
- 调用 VBScript 计算简单的四则混合运算数学题
- 反向工程之四则混合运算优先级判断--加括号问题
- 中缀/后缀表达式转换-使用四则混合运算表达式生成树
- 表达式运算,四则混合运算
- java四则混合运算工具类备忘
- 四则运算生成器功能完善&&界面设计——结对项目
- 用Visual C# 实现四则混合运算2
- 实现一个正整数加、减、乘、除四则混合运算求值方法
- 简单的四则运算(续)
- java语言的科学与艺术-编程练习---简单的四则运算计算器
- 简单的四则运算
- 简单的四则运算题目生成及求值小程序
- [C++]利用逆波兰式,简单实现下加减乘除的混合运算
- 整数四则混合运算-随机口算试题 Excel 单元格公式
- 一个简单的四则运算程序C语言实现--实现处理括号
- 四则混合运算3
- 简单的四则运算答题系统(Java版)