gpt4 book ai didi

bison - flex/bison 将数字解释为 float

转载 作者:行者123 更新时间:2023-12-01 18:04:53 32 4
gpt4 key购买 nike

我正在尝试实现一个可以进行浮点运算的 Flex/bison 计算器。我的 Flex 代码如下所示

%{
#include "calc.tab.h"
#include <stdlib.h>

void yyerror(char *s);
%}

digit [0-9]
integer {digit}+
real ({digit}+[.]{digit}*)|({digit}*[.]{digit}+)
exp ({integer}|{real})[eE]-?{integer}

%%

({integer}|{real}|{exp}) { yylval = atof(yytext); return NUMBER; }
[-+*/\n] { return *yytext; }
[ \t\v\f\r] { }
. { yyerror("Unknown Character"); }

%%

int yywrap(void)
{
return 1;
}

我的 Bison 代码看起来像这样

%{
#include <stdio.h>

typedef double YYSTYPE;
#define YYSTYPE_IS_DECLARED

void yyerror(char *s);
extern char *yytext;
extern int yylineno;
%}

%token NUMBER

%left '+' '-'
%left '*' '/'

%%

program: program expr '\n' { printf("%g\n", $2); }
| program '\n'
|
;
expr: expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| NUMBER { $$ = $1; }
;

%%

void yyerror(char *s)
{
fprintf(stderr, "error: %s at %s, line %d\n", s, yytext, yylineno);
}

int main(int argc, char *argv[])
{
yyparse();

return 0;
}

这不会产生正确的输出。即使词法分析器将字符串解释为 double 并将它们正确存储在 yylval 中变量,当解析器将数字相加时,它只输出 0.0000 。但是,如果我声明 yylval作为一个工会通过 %union仅包含一个 double lf_val; 的指令变量,并存储atof在此字段中输出yylval在词法分析器中并声明 %token <lf_val> NUMBER%type <lf_val> expr在解析器中,一切似乎都正常。

但是,为什么 typedef 的简单方法不可以呢? ing YYSTYPE工作?我也尝试过#define YYSTYPE double 。这也不起作用。

最佳答案

关于%codeBison's documentation状态:

%code requires [...] is the best place to override Bison's default YYSTYPE
and YYLTYPE definitions.

所以只需在您的 Bison 文件顶部添加以下内容:

%code requires
{
#define YYSTYPE double
}

您还需要删除这两行:

typedef double YYSTYPE;
#define YYSTYPE_IS_DECLARED

请注意,据我所知,YYSTYPE_IS_DECLARED 没有在任何地方记录,因此仅供 Bison 内部使用。

如果您不熟悉在简单的 %{ 序言中使用 Bison 的 %code 指令,您可能会发现 this section of the documentation读起来很有趣。

关于bison - flex/bison 将数字解释为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14462808/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com