看板 Programming 關於我們 聯絡資訊
先附上程式碼: Lex: %{ #include <stdio.h> #include "y.tab.h" %} %option noyywrap %% [0-9]+ { yylval = atoi(yytext); return INTEGER; } [\+\-\*\/\(\)\n] { return *yytext; } [\t] {} . { yyerror("invalid char."); } %% Yacc: %{ #include <stdio.h> #include <stdlib.h> #include "y.tab.h" int yylex(); %} %token INTEGER %left '+' '-' %left '*' '/' %nonassoc UMINUS %% program: |program expression '\n' { printf("Ans : %d\n\n", $2); } ; expression : INTEGER { $$ = $1; } | expression '+' expression { $$ = $1 + $3; printf("%d + %d = %d \n",$1,$3,$$);} | expression '-' expression { $$ = $1 - $3; printf("%d - %d = %d \n",$1,$3,$$);} | expression '*' expression { $$ = $1 * $3; printf("%d * %d = %d \n",$1,$3,$$);} | expression '/' expression { $$ = $1 / $3; printf("%d / %d = %d \n",$1,$3,$$);} | '-' expression %prec UMINUS { $$ = -$2; } | '(' expression ')' { $$ = $2; } | { yyerror("invalid input.\n"); } ; %% int main() { yyparse(); return 0; } void yyerror(char *msg) { printf("Error: %s \n",msg); } 要實現 +-*/()和負數四則運算 不知道為什麼最後會出現 syntax error https://i.imgur.com/PkahB5J.jpg 搞整個週末了實在沒辦法只能求大神了 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.10.237.189 ※ 文章網址: https://www.ptt.cc/bbs/Programming/M.1544986680.A.BAF.html ※ 編輯: aa1727 (39.10.237.189), 12/17/2018 02:59:02
CindyLinz: 你 program 沒有可以結束的 rule 啊 112.121.78.5 12/17 14:29