Bison:float = int / int

问题描述 投票:0回答:1

我正在学习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=$1; 
        printf("In pgm %f \n",div_result);
    } ;
expr : factor TOKEN_DIV factor
    { 
        printf("In expr %f \n",(float)$1/(float)$3); 
        $$ = (float)$1 / (float)$3;
    } ;
factor: TOKEN_INT { $$ = atoi(yytext); } ;
%%

int main() { yyparse(); }

在expr规则中,printf输出是正确的。例如,如果输入为7/3,则打印输出为2.333333。但在程序规则中,printf输出为2.000000。 似乎expr规则中的$$或程序规则中的$ 1是int类型。对 ?为什么?

bison
1个回答
1
投票

因为int是所有语义值的默认类型,除非您指定其他内容。有关详细信息,请参阅bison manual

如该链接所示,它可以像添加一样简单

%define api.value.type {double}

不要使用float。 C中的“正常”浮点表示是doublefloat太不精确,无法用于大多数目的;它应该只用于可以容忍不精确的非常特定的应用。

© www.soinside.com 2019 - 2024. All rights reserved.