I am making a basic calculator in Flex/Bison and I want to do exponentials (^) but my current implementation is not working, can anyone tell me why not and how to fix it?

%{
    #include <stdio.h>
    #include <math.h>
    void yyerror(char *);
    int yylex(void);
    int symbol;
%}

%token INTEGER VARIABLE
%left '+' '-' '*' '/' '^'

%%

program:
    program statement '\n'
    | /* NULL */
    ;
statement:
    expression          { printf("%d\n", $1); }
    | VARIABLE '=' expression   { symbol = $3; }
    ;
expression:
        INTEGER

    | VARIABLE          { $$ = symbol; }
    | '-' expression        { $$ = -$2; }
    | expression '+' expression { $$ = $1 + $3; }
    | expression '-' expression { $$ = $1 - $3; }
    | expression '*' expression { $$ = $1 * $3; }
    | expression '/' expression { $$ = $1 / $3; }
    | expression '^' expression { $$ = $1 ^ $3; }
    | '(' expression ')'        { $$ = $2; }
    ;

%%

void yyerror(char *s) {
    fprintf(stderr, "%s\n", s);
}
int main(void) {
    yyparse();
}

Thanks

有帮助吗?

解决方案

^ is not the exponential operator in C; it's xor. You need to use the math library function pow or write your own integer exponentiation function.

其他提示

I think this would work

 $$=pow($1,$3);

For more details, refer: http://www-h.eng.cam.ac.uk/help/tpl/languages/flexbison/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top