我想做一个简单的计算器,将值计算为 3+4 或 5/8,但我在使用数学函数的 abs 方面遇到了问题。我的代码如下:
野牛文件:
%{
#include <stdio.h>
#include <math.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL {
printf("= %dn", $2);
}
;
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER
| ABS term {$$=fabs($2)}
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %sn", s);
}
和 Flex 文件
%{
# include "calc.tab.h"
%}
/* recognize tokens for the calculator and print them out */
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"@" { return ABS; }
[0-9]+ { yylval = atoi(yytext);
return NUMBER;
}
n { return EOL; }
[ t] { /* ignore whitespace */ }
. {
printf("Mystery character %cn", *yytext);
}
%%
yywrap()
{
}
我选择了 @ 符号作为绝对值,但我的程序确实可以识别以下表达式:
4+@5,但不像4+@-5
我应该在我的程序中更改什么,以便它识别此运算符?
运算符定义似乎@
正确。但是,您的语言定义不接受一元减号,即您的代码不能接受类似4+-5
没有@
的东西。您需要添加适当的语言定义以支持一元减号。(如果需要,一元加(。有关一元运算符的详细信息,以及它们与二进制运算符的不同之处,您可以在 wiki 上阅读一元运算符。
您可以尝试以下操作:
term: NUMBER
| ABS term {$$ = fabs($2); }
| SUB term {$$ = -$2; }
;