野牛:float = int / int
Bison : float = int / int
我正在学习 Bison/Flex,但我不明白如何强制 $$ 类型在 .y 文件中成为浮点数。
scanner.l 文件
%{
#include "token.h"
%}
%%
[0-9]+ { return TOKEN_INT; }
"/" { return TOKEN_DIV; }
%%
int yywrap() { return 1; }
parser.y 文件
%{
#include <stdio.h>
void yyerror(char const *s) {} ;
extern char *yytext;
%}
%token TOKEN_INT
%token TOKEN_DIV
%%
program : expr
{
float div_result;
div_result=;
printf("In pgm %f \n",div_result);
} ;
expr : factor TOKEN_DIV factor
{
printf("In expr %f \n",(float)/(float));
$$ = (float) / (float);
} ;
factor: TOKEN_INT { $$ = atoi(yytext); } ;
%%
int main() { yyparse(); }
在expr规则中,printf输出是正确的。例如,如果输入为 7/3,则打印输出为 2.333333。但是在program rule中,printf的输出是2.000000.
expr rule中的$$或者program rule中的$1好像是int类型。正确的 ?为什么?
因为 int
是所有语义值的默认类型,除非您指定其他内容。有关详细信息,请参阅 bison manual。
如 link 所示,只需添加
%define api.value.type {double}
不要使用 float
。 C中的"normal"浮点表示是double
。 float
太不精确,无法用于大多数目的;它应该只用于非常特殊的应用程序,在这些应用程序中可以容忍不精确性。
我正在学习 Bison/Flex,但我不明白如何强制 $$ 类型在 .y 文件中成为浮点数。
scanner.l 文件
%{
#include "token.h"
%}
%%
[0-9]+ { return TOKEN_INT; }
"/" { return TOKEN_DIV; }
%%
int yywrap() { return 1; }
parser.y 文件
%{
#include <stdio.h>
void yyerror(char const *s) {} ;
extern char *yytext;
%}
%token TOKEN_INT
%token TOKEN_DIV
%%
program : expr
{
float div_result;
div_result=;
printf("In pgm %f \n",div_result);
} ;
expr : factor TOKEN_DIV factor
{
printf("In expr %f \n",(float)/(float));
$$ = (float) / (float);
} ;
factor: TOKEN_INT { $$ = atoi(yytext); } ;
%%
int main() { yyparse(); }
在expr规则中,printf输出是正确的。例如,如果输入为 7/3,则打印输出为 2.333333。但是在program rule中,printf的输出是2.000000.
expr rule中的$$或者program rule中的$1好像是int类型。正确的 ?为什么?
因为 int
是所有语义值的默认类型,除非您指定其他内容。有关详细信息,请参阅 bison manual。
如 link 所示,只需添加
%define api.value.type {double}
不要使用 float
。 C中的"normal"浮点表示是double
。 float
太不精确,无法用于大多数目的;它应该只用于非常特殊的应用程序,在这些应用程序中可以容忍不精确性。