逆波兰记号计算器【文件名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: '\n'
| exp '\n' { printf ("\t%.10g\n", $); }
; exp: NUM { $$ = $; }
| exp exp '+' { $$ = $ + $; }
| exp exp '-' { $$ = $ - $; }
| exp exp '*' { $$ = $ * $; }
| exp exp '/' { $$ = $ / $; }
/* Exponentiation */
| exp exp '^' { $$ = pow($, $); }
/* Unary minus */
| exp 'n' { $$ = -$; }
;
%% #include <ctype.h> int yylex (void) {
int c; /* Skip white space. */
while ((c = getchar ()) == ' ' || c == '\t') ; /* Process numbers. */
if (c == '.' || isdigit (c)) {
ungetc (c, stdin);
scanf ("%lf", &yylval);
return NUM;
} /* Return end-of-input. */
if (c == EOF) return ; /* Return a single char. */
return c;
} void yyerror (char const *s) {
fprintf (stderr, "%s\n", 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:
'\n'
| exp '\n' { printf ("\t%.10g\n", $); }
;
exp:
NUM { $$ = $; }
| exp '+' exp { $$ = $ + $; }
| exp '-' exp { $$ = $ - $; }
| exp '*' exp { $$ = $ * $; }
| exp '/' exp { $$ = $ / $; }
| '-' exp { $$ = -$; }
| exp '^' exp { $$ = pow ($, $); }
| '(' exp ')' { $$ = $; }
;
%% #include <ctype.h> int yylex (void) {
int c; /* Skip white space. */
while ((c = getchar ()) == ' ' || c == '\t') ; /* Process numbers. */
if (c == '.' || isdigit (c)) {
ungetc (c, stdin);
scanf ("%lf", &yylval);
return NUM;
} /* Return end-of-input. */
if (c == EOF) return ; /* Return a single char. */
return c;
} void yyerror (char const *s) {
fprintf (stderr, "%s\n", s);
} int main (void) {
return yyparse ();
} ------------------运行----------------------
bison calc.y
gcc -o calc -lm calc.tab.c
./calc
8*(1+3)
     32
05-11 11:04