zoukankan      html  css  js  c++  java
  • bison实例

    逆波兰记号计算器【文件名rpcalc.y】

    %{ #define YYSTYPE double #include <stdio.h> #include <math.h> #include <ctype.h> int yylex (void); void yyerror (char const *); %} %token NUM %% input: /* empty */ | input line ; line: ' ' | exp ' ' { printf (" %.10g ", $1); } ; exp: NUM { $$ = $1; } | exp exp '+' { $$ = $1 + $2; } | exp exp '-' { $$ = $1 - $2; } | exp exp '*' { $$ = $1 * $2; } | exp exp '/' { $$ = $1 / $2; } /* Exponentiation */ | exp exp '^' { $$ = pow($1, $2); } /* Unary minus */ | exp 'n' { $$ = -$1; } ; %% #include <ctype.h> int yylex (void) { int c; /* Skip white space. */ while ((c = getchar ()) == ' ' || c == ' ') ; /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } /* Return end-of-input. */ if (c == EOF) return 0; /* Return a single char. */ return c; } void yyerror (char const *s) { fprintf (stderr, "%s ", s); } int main (void) { return yyparse (); }

    ------------------运行----------------------
    bison rpcalc.y
    gcc -o rpcalc -lm rpcalc.tab.c
    ./rpcalc
    4 9 +
         13
     
    中辍符号计算器【文件名calc.y】

    %{ #define YYSTYPE double #include <math.h> #include <stdio.h> int yylex (void); void yyerror (char const *); %} /* Bison declarations. */ %token NUM %left '-' '+' %left '*' '/' %right '^' /* exponentiation */ %% /* The grammar follows. */ input: | input line ; line: ' ' | exp ' ' { printf (" %.10g ", $1); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp { $$ = -$2; } | exp '^' exp { $$ = pow ($1, $3); } | '(' exp ')' { $$ = $2; } ; %% #include <ctype.h> int yylex (void) { int c; /* Skip white space. */ while ((c = getchar ()) == ' ' || c == ' ') ; /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } /* Return end-of-input. */ if (c == EOF) return 0; /* Return a single char. */ return c; } void yyerror (char const *s) { fprintf (stderr, "%s ", s); } int main (void) { return yyparse (); }

    ------------------运行----------------------
    bison calc.y
    gcc -o calc -lm calc.tab.c
    ./calc
    8*(1+3)
         32
  • 相关阅读:
    只因写了一段爬虫,公司200多人被抓!
    中国顶级程序员图鉴
    漫画 | 外行对程序员误会有多深!
    关于深夜技术事故纪实录的若干问题回复
    富士康14跳被我赶上了,流水线车间真的没有梦想 | 十年系列
    祖国和我们小山村的希望
    互联网从此没有 BAT
    程序员,职场上请远离这种人!
    HTML5漂亮实用的电子书
    这个jQuery导航菜单怎么样
  • 原文地址:https://www.cnblogs.com/xiaozong/p/6289807.html
Copyright © 2011-2022 走看看