【问题标题】:Flex and Bison Calculator if issues如果出现问题,请使用 Flex 和 Bison 计算器
【发布时间】:2014-03-05 22:22:08
【问题描述】:

如果有人试图除以 0,我试图让我的计算器给出“INF”的答案,但 if 语句不起作用。 op == '/' 和 b == 0 都单独工作,但不能与 && 一起工作。相反,它会使 exe 停止工作。

弹性文件:

%{
#include <stdio.h>
#include <stdlib.h>
#include "y.tab.h"
extern  FILE* yyin;
        FILE* FileOutput;
#define YYSTYPE int
%}

%%

[0-9]+  { yylval = (int)strtol(yytext, NULL, 10); return INTEGER; }
"+" return ADD;
"-" return SUBTRACT;
"*" return MULTIPLY;
"/" return DIVIDE;
[ \t]  ;
.       yyerror();

%%

int main(int argc, char *argv[])
{
yyin = fopen(argv[1], "r");
FileOutput = fopen("output.c", "w");
yyparse();
fclose(FileOutput);
return 0;
}

int yywrap(void)
{
 return 1;
}

int yyerror(void)
{
 //printf("Error\n");
}

野牛文件:

%{
 #include <stdio.h>
 #include <stdlib.h>
 extern FILE* FileOutput;
 #define YYSTYPE int

 void createcode(int result, int a, unsigned char op, int b);

%}



%token INTEGER
%token ADD SUBTRACT MULTIPLY DIVIDE

%left ADD SUBTRACT
%left MULTIPLY DIVIDE


%%
program: 
    | program statement
    ;

statement:
    expression '\n'     { printf("%d\n", $1); }
    | error '\n'            { yyerrok; }
    ;

expression: 
    INTEGER         { $$ = $1; }
    | expression ADD expression     { $$ = $1 + $3, createcode($$, $1, '+', $3);}
    | expression SUBTRACT expression        { $$ = $1 - $3; createcode($$, $1, '-', $3);}
    | expression MULTIPLY expression        { $$ = $1 * $3; createcode($$, $1, '*', $3);}
    | expression DIVIDE expression      { $$ = $1 / $3; createcode($$, $1, '/', $3);}
    | '(' expression ')'            { $$ = $2; }
    ;

%%

void createcode(int result, int a, unsigned char op, int b)
{
if (op == '/' && b == 0)
    printf("INF");
else
    printf("%d %c %d = %d\n", a, op, b, result);
}

【问题讨论】:

  • “exe 停止工作”是因为 $$ = $1 / $3,它是被零除。这发生在 createcode 甚至被调用之前。
  • 我想你想把计算移到createcode

标签: c compiler-construction bison flex-lexer


【解决方案1】:

正如 cmets 中所说,除以 0 会使程序崩溃。如果你真的想做你在问题中解释的事情,我会将$$ = $1/$3 替换为$$ = ($3 == 0) ? 0 : $1/$3 之类的东西。但这并不令人满意,因为int 没有特殊值(NaN 行用于float)来指示错误结果。

但是我认为这不是一件好事,你应该让程序崩溃。从数学上讲,除以 0 并不等于无穷大,它实际上是未定义的,因为当你越过 0 时,它会从 -infinity 翻转到 +infinity。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多