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
  • 相关阅读:
    ibernate学习笔记5---实体类或属性名与数据库关键字冲突、hql命名参数、hql实现通用分页
    dom4j API使用简介
    oracle创建表空间、创建用户、授权、夺权、删除用户、删除表空间
    一、导入、导出远程Oracle数据库
    JavaScript 类的定义和引用 JavaScript高级培训 自定义对象
    实现JavaScript中继承的三种方式
    JavaScript 高级篇之闭包、模拟类,继承(五)
    IE JS编程需注意的内存释放问题
    浅谈javascript中的作用域
    LeetCode----Path Sum
  • 原文地址:https://www.cnblogs.com/xiaozong/p/6289807.html
Copyright © 2011-2022 走看看