代碼地址:我的GIS/CS學習筆記:https://github.com/yunwei37/myClassNotes
<一個浙大GIS/CS小白的課程學習筆記 >
要求
生成如下文法表示的表達式對應的計算器
exp->exp + exp | exp – exp
| exp * exp |exp / exp
|exp ^ exp | - exp
|(exp) |NUM
對於輸入的中綴表達式,要給出結果。如 3 +(4 * 5)結果應爲 23。要求能連續處理若干個數學表達式,直到輸入結束或文件結束。
lex
%{
#include <stdio.h>
#include "y.tab.h"
%}
%option noyywrap
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
[^ \t\n] {
return yytext[0];
}
\n {
return yytext[0];
}
. {}
%%
yacc
%{
#include <stdio.h>
#include <ctype.h>
#include <math.h>
%}
%code requires {
#define YYLTYPE int
#define YYSTYPE int
}
%token NUMBER
%%
command : exp1 {
}
;
exp1: exp1 '\n' exp {
printf("%d\n", $3);
}
| exp {
printf("%d\n", $1);
};
exp : exp '+' term {
$$ = $1 + $3;
}
| exp '-' term {
$$ = $1 - $3;
}
| term { $$ = $1; }
;
term : term '*' factor {
$$ = $1 * $3;
}
| term '/' factor {
$$ = $1 / $3;
}
| factor { $$ = $1; }
;
factor : '-' numfactor {
$$ = - $2;
}
| numfactor '^' numfactor {
$$ = pow($1 , $3);
}
| numfactor { $$ = $1; }
;
numfactor : NUMBER { $$ = $1; }
| '(' exp ')' { $$ = $2; }
;
%%
int main() {
yyparse();
}
int yyerror(char *s) {
fprintf(stderr, "%s\n", s);
return 0;
}