Today, when I read "Compiling principles and practices", I saw a simple integer calculator implementation.
Following the book's thinking, I expanded slightly:
1. Extend from the integer calculator to the decimal calculator.
2. Support Division
3, support null characters.
The results are as follows:
The code is simple, as follows:
CAL.C:
#include <stdio.h> #include <stdlib.h>char token;double exp (void);d ouble term (void);d ouble factor (void); Char Getprintablechar (void), void match (char expectedtoken), void error (void), int main (void) {double result;for (;;) {token = Getprintablechar (), if (token = = ' Q ') Break;result = exp (), if (token = = ' \ n ') printf ("Result is:%g\n", result); else Error ();} return 0;} Double exp (void) {Double temp = term (), while (token = = ' + ' | | token = = ' – ') switch (token) {case ' + ': match (' + '); Temp + = term (); Break;case '-': Match ('-'); Temp-= term (); break;} return temp;} Double term (void) {Double temp = factor (), while (token = = ' * ' | | token = = "/') switch (token) {case ' * ': Match (' * '); Temp *= factor (); Break;case '/': Match ('/'); Temp/= factor (); break;} return temp;} Double factor (void) {double Temp;if (token = = ' (') {match ('); temp = exp (); match (') ');} else if (IsDigit (token)) {ungetc ( token, stdin); scanf ("%lf", &temp); token = Getprintablechar ();} Elseerror (); return temp;} void error (void) {fprintf (stderr, "error!\n"); exit (exit_failure);} void Match (char expectedtoken) {if (Expectedtoken = = token) token = Getprintablechar (); Elseerror ();} Char Getprintablechar (void) {char temp;dotemp = GetChar (); while (Isblank (temp)); return temp;}
The idea of program realization is to implement according to EBNF rule, namely:
<exp> <term> {<addop> <term>}<addop> + | -<term> <factor> {<mulop> <factor>}<mulop> * | /<factor> (<exp>) | Number
About EBNF, can be the contents of reference books, here will not repeat.
C Language implementation of a calculator