gpt4 book ai didi

c - 计算器中的错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:57 24 4
gpt4 key购买 nike

我尝试学习 flex 和 bison,但我的 flex/bison 计算器打印出错误的结果。示例

$ ./fb1-5 
1 + 2 + 3
= 32728

生成文件

fb1-5:  fb1-5.l fb1-5.y
bison -d fb1-5.y
flex fb1-5.l
cc -o $@ fb1-5.tab.c lex.yy.c -lfl

词法分析器

%{
# include "fb1-5.tab.h"
%}
%%
"+" { 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 %c\n", *yytext); }
%%

解析器

/* 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("= %d\n", $1); }
;
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 { $$ = $2 >= 0? $2 : - $2; }
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}

可能是什么问题?

最佳答案

在与 calclist 关联的操作中,您引用了 $1 的值,它指的是递归产生式规则的 calclist 部分。但是,您实际上从未在任何地方为 calclist 非终结符赋值。你是说 2 美元吗?

关于c - 计算器中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749419/

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