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
  • 相关阅读:
    思考的乐趣
    编程的知识体系
    Android用Intent来启动Service报“java.lang.IllegalArgumentException: Service Intent must be explicit”错误的解决方法
    手拼SQL小技巧,WHERE 1=1
    n+1 < n , are you sure?
    java swing 去掉按钮文字周围的焦点框
    MyBatis使用动态SQL标签的小陷阱
    String、StringBuffer、StringBuilder的一些小经验……
    SQL Server 2012安装后找不到服务器名称的解决办法!!!
    CSS元素水平垂直居中方法总结(主要对大漠以及张鑫旭博客所述方法进行了归纳)
  • 原文地址:https://www.cnblogs.com/xiaozong/p/6289807.html
Copyright © 2011-2022 走看看