C Language implementation of a calculator

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.