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
  • 相关阅读:
    理解java容器:iterator与collection,容器的起源
    【软件构造】-<笔记>-浅谈java中类的初始化过程
    CSAPP HITICS 大作业 hello's P2P by zsz
    2年经验,java后端必备技术点总结(脑图)
    手把手教,手写AVL树
    Redis源码分析-底层数据结构盘点
    验证mysql事务隔离级别机制加锁情况与MVCC机制
    Layui镜像站
    elasticsearch技术实战——第一篇(使用篇)
    【基础1】JniHelper静态函数和非静态函数的调用
  • 原文地址:https://www.cnblogs.com/xiaozong/p/6289807.html
Copyright © 2011-2022 走看看