【问题标题】:Calculator using Lex and Yacc使用 Lex 和 Yacc 的计算器
【发布时间】:2017-11-16 13:40:42
【问题描述】:

是否可以在 lex 和 Yacc 中构造一个简单的算术计算器?

如果是,请在继续之前列出我应该理解的概念/方法。

【问题讨论】:

  • 在发布问题之前,您应该对其进行搜索
  • @Billa 我做了,但我的声望低于 15,所以我的点赞没有显示出来!非常感谢,顺便说一句!
  • 我很高兴听到它有帮助。

标签: automata


【解决方案1】:

Reference

注意:在发布问题之前,您应该搜索一下,我要发布的以下答案是从上面的链接中获得的,该链接是我从谷歌搜索中获得的。

以下代码用于实现使用YACC和LEX的计算器程序。

cal.l

DIGIT [0-9]+\.?|[0-9]*\.[0-9]+

%option noyywrap

%%

[ ]
{DIGIT} { yylval=atof(yytext); return NUM;}
\n|. {return yytext[0];}

cal.y

%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM

%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%right UMINUS

%%

S : S E ‘\n’ { printf(“Answer: %g \nEnter:\n”, $2); }
| S ‘\n’
|
| error ‘\n’ { yyerror(“Error: Enter once more…\n” );yyerrok; }
;
E : E ‘+’ E { $$ = $1 + $3; }
| E’-‘E { $$=$1-$3; }
| E’*’E { $$=$1*$3; }
| E’/’E { $$=$1/$3; }
| ‘(‘E’)’ { $$=$2; }
| ‘-‘E %prec UMINUS { $$= -$2; }
| NUM
;
%%

#include “lex.yy.c”

int main()
{
printf(“Enter the expression: “);
yyparse();
}

yyerror (char * s)
{
printf (“% s \n”, s);
exit (1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多