【发布时间】: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