I wrote a complete calculator.

Source: Internet
Author: User

There are three mathematical expressions: prefix expressions, infix expressions, and suffix expressions.

The infix expression is what we usually see, such as 4 + 2*5-7/11. This operator is easy to calculate, but the computation is complicated. For computers, it is best to convert this expression to a prefix expression or a suffix expression before computation.

Before writing a calculator, you must first know the basic knowledge:

1. The infix expression is converted to the suffix expression.

For example:

4 + 2*5-7/11 this is an infix expression, and its suffix expression is: 4 2 5*7 11/-+. (or 4 2 5 * + 7 11 /-)

In fact, it is also very simple. The infix expression is actually the in-order traversal of the Binary Tree corresponding to the expression. The suffix expression is the post-order traversal of the binary tree, And the prefix expression is the pre-order traversal.

Basic Idea of algorithms:
Three arrays are used. One array stores the input expression (infix expression), one array stores the suffix expression, and the other array acts as the operator stack.
The infix expression is scanned from start to end to process different types of characters according to different situations;
1. If it is a number, it is directly placed into the suffix expression array;
2. if it is left parentheses, it is directly written into the stack;
3. If it is a right brace, the operators from the top of the stack to the corresponding left brace will be removed from the stack [put into the suffix expression array], and the corresponding left brace will be cleared;
4. For an operator, if the priority of the operator is greater than the top priority of the stack, the operator goes directly to the stack;If the operator priority is less than or equal to the top of the stack, the top of the stack operator is first output to the stack, written to the suffix expression array, and then re-written to the stack;If the operator priority is less than or equal to the top of the stack, the top of the stack operator is first output to the stack, written to the suffix expression array, repeat this operation, until the priority of the operator is higher than that of the top-stack operator, and then the operator is added to the stack. (thanks to test of liwenhaosuper.
Case, the error has been corrected and the corresponding code has been modified)
5. After scanning, retrieve all operators in the stack and write the suffix expression array.
Note: Operator priority: *,/greater than +,-greater (

2. Calculate the suffix expression
Algorithm idea:
Evaluate a suffix expression is simpler than simply evaluate an infix expression. In a suffix expression, parentheses are not required, and the operator priority is no longer effective. Operations such as stack operations can be completed through simple out-of-stack operations.
1. Initialize an empty Stack
2. Read the suffix expression from left to right
3. If the character is an operand, press it into the stack.
4. If the character is an operator, two operands are displayed, perform the appropriate operation, and then press the result into the stack. If you cannot bring up two operands, the syntax of the suffix expression is incorrect.
5. The result is displayed from the stack at the end of the suffix expression. If the suffix expression format is correct, the stack should be empty.

The calculator program is as follows: This program can calculate non-negative mathematical expressions and calculate non-integers. If the input is valid, the result is retained with two decimal places.

# Include <stdio. h> # include <stdlib. h> # define max_len 80 void convert2postfix (char * SRC, char * DST); float CAL (char * SRC); int main () {char str1 [max_len], str2 [max_len]; float res; gets (str1); convert2postfix (str1, str2); printf ("src: % s \ n", str1); printf ("DST: % s \ n ", str2); Res = CAL (str2); printf (" Result: %. 2f \ n ", Res); Return 0;} // The infix expression is converted to a suffix expression (the operator and the operand should be separated by spaces) void convert2postfix (char * SRC, char * DST) {char * Psrc, * pdst; char stack [max_len]; int top; Top =-1; psrc = SRC; pdst = DST; while (* psrc! = '\ 0') {If (* psrc> = '0' & * psrc <= '9') {* pdst = * psrc; pdst ++; // Add the separator space if (! (* (Psrc + 1)> = '0' & * (psrc + 1) <= '9') & * (psrc + 1 )! = '. ') {* Pdst = ''; pdst ++ ;}} if (* psrc = '. ') {* pdst = * psrc; pdst ++;} If (* psrc =' (') {stack [++ top] = * psrc ;} if (* psrc = ') {While (stack [Top]! = '(') {* Pdst = stack [top --]; pdst ++; // Add a space to separate * pdst = ''; pdst ++ ;} // pop up '('top --;} If (* psrc =' * '| * psrc = '/') {If (stack [Top] = '*' | stack [Top] = '/') {* pdst = stack [top --]; pdst ++; // Add the separator space * pdst = ''; pdst ++;} stack [++ top] = * psrc ;} if (* psrc = '+' | * psrc = '-') {While (stack [Top] = '*' | stack [Top] = '/' | stack [Top] = '+' | stack [Top] = '-') {* pdst = stack [Top- -]; Pdst ++; // Add a separator space * pdst = ''; pdst ++;} stack [++ top] = * psrc;} psrc ++ ;} // After scanning, all operators in the stack are taken out and the suffix expression array is written. While (top! =-1) {* pdst = stack [top --]; * pdst ++; * pdst = ''; pdst ++;} * pdst = '\ 0 ';} // calculate the suffix expression float CAL (char * SRC) {float stack [max_len]; float opd1, opd2; int top; char * P, * pre; Top =-1; P = SRC; while (* P! = '\ 0') {If (* P> = '0' & * P <= '9') {pre = P; while (* P> = '0' & * P <= '9') | * P = '. ') {P ++;} * P =' \ 0'; stack [++ top] = atof (pre );} if (* P = '+' | * P = '-' | * P = '*' | * P = '/') {opd2 = stack [top --]; opd1 = stack [top --]; Switch (* P) {Case '+': stack [++ top] = opd1 + opd2; break; Case '-': stack [+ TOP] = opd1-opd2; break; Case '*': stack [+ TOP] = opd1 * opd2; break; case '/': // more strict. When the divisor is 0, stack [++ top] = opd1/opd2; break ;}} P ++ ;} return stack [top --];}

Repost this article please indicate the author and the source [Gary's influence] http://garyelephant.me, do not for any commercial purposes!

Author: Gary Gao focuses on the internet, distributed, high concurrency, automation, and software teams

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.