C language implementation of a calculator
Today, I read compilation principles and practices and saw the implementation of a simple Integer Calculator.
Based on the ideas in the book, I made some extensions:
1. Extend From Integer Calculator to decimal calculator.
2. Division is supported.
3. Empty characters are supported.
The running effect is as follows:
The Code is as follows: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + Y2FsLmM6PC9wPgo8cD48cHJlIGNsYXNzPQ = "brush: java;" >#include # Include Char token; double exp (void); double term (void); double 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); elseerror ();} 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 program implementation logic is implemented according to the EBNF rules, namely:
->
{
} -> + | -
->
{
}
-> * | /
-> (
) | Number
We will not go into details about EBNF here.