%{
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define YYSTYPE double
%}
%token number
%left '-' '+'
%left '*' '/'
%right '^'
%right NEG
%%
input: /* empty string */
| input exp '\n'{printf("Result %lf\n",$2);}
| error '\n'{printf("Invalid Expression\n",$2);}
;
exp: exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = pow ($1, $3); }
| '(' exp ')' { $$ = $2; }
| number { $$ = $1; }
;
%%
yylex()
{
char c;
while((c=getchar())==' ');
if(isdigit(c)){
ungetc(c,stdin);
scanf("%lf",&yylval);
return number;
}
return c;
}
int main()
{
printf("\nEnter an arithmetic expression:\n\n");
yyparse();
return 0;
}
int yywrap()
{
return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define YYSTYPE double
%}
%token number
%left '-' '+'
%left '*' '/'
%right '^'
%right NEG
%%
input: /* empty string */
| input exp '\n'{printf("Result %lf\n",$2);}
| error '\n'{printf("Invalid Expression\n",$2);}
;
exp: exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = pow ($1, $3); }
| '(' exp ')' { $$ = $2; }
| number { $$ = $1; }
;
%%
yylex()
{
char c;
while((c=getchar())==' ');
if(isdigit(c)){
ungetc(c,stdin);
scanf("%lf",&yylval);
return number;
}
return c;
}
int main()
{
printf("\nEnter an arithmetic expression:\n\n");
yyparse();
return 0;
}
int yywrap()
{
return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}
No comments:
Post a Comment