-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc2.y
More file actions
65 lines (39 loc) · 738 Bytes
/
calc2.y
File metadata and controls
65 lines (39 loc) · 738 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
%{
#include <stdio.h>
#include <stdlib.h>
extern int yylex();
extern int yyparse();
void yyerror(const char* x);
%}
%union
{
int valI;
float valF;
}
;
%token<valI> IntegerExpr
%token ADD MULT SUBTRACT DIVIDE NEWLINE
%type<valI> IntExpr
%start calc
%%
calc:
|calc line
;
line: NEWLINE
|IntExpr NEWLINE {float ans=$1; int k=ans;if(k==ans){printf("%d\n",k);}
else{printf("%f\n",ans);}}
;
IntExpr: IntegerExpr {$$=$1;}
|IntExpr IntExpr ADD {$$=$1+$2;}
|IntExpr IntExpr SUBTRACT {$$=$1-$2;}
|IntExpr IntExpr MULT {$$=$1*$2;}
|IntExpr IntExpr DIVIDE {$$=$1/$2;}
;
%%
int main() {
yyparse();
return 0;}
void yyerror(const char* x){
fprintf(stderr,"ERROR:%s\n",x);
exit(1);
}