十进制数的 flex 输出问题
problem with flex output with decimal numbers
我正在用 Flex 和 Bison 编写一个小型浮点数计算器。到目前为止,我的代码如下:
弹性代码
%{
# include "prb1.tab.h"
float yylval;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+(\.[0-9]+)? { yylval = atof(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
yywrap()
{
}
/*main(int argc, char **argv)
{
int tok;
while(tok = yylex()) {
printf("%d", tok);
if(tok == NUMBER) printf(" = %f\n", yylval);
else printf("\n");
}
}*/
野牛代码
/* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL { printf("= %f\n", ); }
;
exp: factor
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor: term
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term: NUMBER
| ABS term { $$ = >= 0? : - ; }
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
我遇到的问题是当我 运行 程序时答案仍然是整数。如何更改它以将答案显示为浮点数?
谢谢
除非您显式声明语义值类型,否则 bison/yacc 假定语义值具有类型 int
。在你的 flex 文件中声明 yylval
不会改变任何东西,因为 bison 永远不会看到那个文件。 (不过,这会导致未定义的行为,因为 yylval
最终被声明为两种不同的类型。我希望编译器会抱怨这一点。)
您可以像这样在 bison 文件中声明语义值类型:
%define api.value.type {double}
(我使用 double
因为它几乎肯定是你想要的;float
是一种低精度数据类型,只有在你有充分理由的情况下才应该使用它。)
您还应该从 flex 文件中删除 yylval
的声明,因为它将在 bison 生成的头文件中声明。
有关详细信息和代码示例,请参阅 bison manual。
我正在用 Flex 和 Bison 编写一个小型浮点数计算器。到目前为止,我的代码如下: 弹性代码
%{
# include "prb1.tab.h"
float yylval;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+(\.[0-9]+)? { yylval = atof(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
yywrap()
{
}
/*main(int argc, char **argv)
{
int tok;
while(tok = yylex()) {
printf("%d", tok);
if(tok == NUMBER) printf(" = %f\n", yylval);
else printf("\n");
}
}*/
野牛代码
/* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL { printf("= %f\n", ); }
;
exp: factor
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor: term
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term: NUMBER
| ABS term { $$ = >= 0? : - ; }
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
我遇到的问题是当我 运行 程序时答案仍然是整数。如何更改它以将答案显示为浮点数?
谢谢
除非您显式声明语义值类型,否则 bison/yacc 假定语义值具有类型 int
。在你的 flex 文件中声明 yylval
不会改变任何东西,因为 bison 永远不会看到那个文件。 (不过,这会导致未定义的行为,因为 yylval
最终被声明为两种不同的类型。我希望编译器会抱怨这一点。)
您可以像这样在 bison 文件中声明语义值类型:
%define api.value.type {double}
(我使用 double
因为它几乎肯定是你想要的;float
是一种低精度数据类型,只有在你有充分理由的情况下才应该使用它。)
您还应该从 flex 文件中删除 yylval
的声明,因为它将在 bison 生成的头文件中声明。
有关详细信息和代码示例,请参阅 bison manual。