I have to write a program that does 2 + 2 = 4 and 2.2 + 2 = 4.2.
I have already done this in such a way as to consider everything as a floating point, but this is "wrong." I have to distinguish them. Here is what I still have:
%{ #include <stdio.h> #include <ctype.h> %} %token <dval> FLOAT %token <ival> INTEGER %union { float dval; int ival; } %type <dval> command exp term factor %% command : exp {printf("%f\n",$1);} ; exp : exp '+' term {$$ = $1 + $3;} | exp '-' term {$$ = $1 - $3;} | term {$$ = $1;} ; term : term '*' factor {$$ = $1 * $3;} | factor {$$ = $1;} ; factor : '(' exp ')' {$$ = $2;} | FLOAT {$$ = $1;} | INTEGER {$$ = $1;} ; %% int main() { return yyparse(); } int yylex() { int c; while( (c=getchar()) == ' '); if( isdigit(c) ) { ungetc(c, stdin); float f1; scanf("%f", &f1); int i1 = (int) f1; if(f1 == 0) { yylval.ival = 0; return INTEGER; } else if( (((float) i1) / f1 ) == 1) { yylval.ival = i1; return INTEGER; } else { yylval.dval = f1; return FLOAT; } //scanf("%f",&yylval.dval); //return(NUMBER); } if(c == '\n') return 0; return c; } int yyerror(char *s) { fprintf(stderr,"%s\n",s); return 0; }
The problem is that each expression can have only 1 type. Now everything is basically floating, therefore, as long as the operations are correct, this is the wrong decision.
I was thinking of defining more expressions, basically having factor_int and factor_float, and then replacing everything in it, but that seems really wrong. I have no idea how to do this, but the tutorials that I saw didnβt really help me.
source share