用yacc做的一个简单的计算器

很简单,就是你输入
3+ 5 * 4 + (345 +2348) * (34 ^ 4)
它会告诉你
3598752871
用yacc做的
代码写的还是不够规范,中间有10个歧义是yacc帮我转换的
编译后整个发布包大小是65k,有需要的把你的邮箱留下

%{ 
#define YYSTYPE double 
#include <math.h>
#include <ctype.h>
#include <stdio.h>

int yylex(void); 
void yyerror (char const*); 
%} 

%token NUM 

%left '+' '-' 
%left '*' '/' 
%left UMINUS 

%% 
input: /* empty */ 
| input line 
; 

line: '\n' 
| exp '\n' {printf ("\t%.10g\n",1);} 
; 

exp: NUM { = 1; } 
| '(' exp ')' { = 2;} 
| exp '+' exp { = 1 + 3; } 
| exp '-' exp { = 1 - 3; } 
| exp '*' exp { = 1 * 3; } 
| exp '/' exp { = 1 / 3; } 

/* Exponentiation */ 
| exp '^' exp { = pow (1,3);} 

/* Unary minus */ 
| '-' exp %prec UMINUS 
{ = -2;} 

; 

%% 

/* The lexical analyzer returns a double floating point 
number on the stack and the token NUM, or the numeric code 
of the character read if not a number. It skips all blanks 
and tabs, and returns 0 for end-of-input. */ 

int yylex (void) { 
    int c; 
    /* Skip white space. */ 
    while ((c = getchar ()) == ' ' || c == '\t') ; 
    /* Process numbers. */ 
    if (c == '.' || isdigit (c)) 
    { 
        ungetc (c, stdin); 
        scanf ("%lf", &yylval); 
        return NUM; 
    } 
    /* Return end-of-input. */ 
    if (c == EOF) return 0; 
    /* Return a single char. */ 
    return c; 
} 

/* Called by yyparse on error. */ 
void yyerror (char const *s) { 
    printf ("%s\n", s); 
} 

int main(void){ 
    return yyparse(); 
}

此博客中的热门博文

少写代码,多读别人写的代码

在windows下使用llvm+clang

tensorflow distributed runtime初窥