Using stack stack to realize calculator experiment Design (c + +) __c++

Source: Internet
Author: User
Tags cos int size pow sin
first, the experimental thinking

1. Enter infix type.
Input format: string, including numbers, operator symbols (including parentheses and English operator names such as Sin).

2. Convert infix to suffix type.
Input: infix format: string
Method: Stack LIFO principle
Stack Ming Chen: symbol stack
Output: Postfix format: String, where there are spaces between the number and the operation symbol, without parentheses.

3. Identify and compute the suffix string into substrings.
Input: Suffix format: string
Method: StringStream, Stack LIFO principle
Stack Name: Data stack
Output: Number format: Double
Explanation: Each substring can only be a number or an operator, if the data is pressed into the data stack, if the operator, then the top of the stack element operation and the results of the operation into the stack. second, the experiment Steps and code realization The following issues are resolved in a step-by-step way:

1. Precedence of Operators
Operator precedence function and implementation code

int priority (char ch)
{
    int p = -3;//initialization
    if (int (ch) >= && int (ch) <= | | ch = = ' E ' | | ch = = ' P ') p =-1;
    The letter priority for the number and the natural number E and pi is-1
    else if (ch = = ' + ' | | | | ch = = ') p = 1;
    To add or subtract a symbol priority of 1
    else if (ch = = ' * ' | | | ch = = '/') p = 2;
    Make the multiplication and division symbol Priority 2
    else if (  ch = = ' ^ ') p = 3;
    The ^ symbol has a priority of 3
    else if (ch = = ' s ' | | | ch = = ' c ' | | ch = = ' t ' | | | ch = = ' L ' | | | ch = = ' o ') p = 5;
    Specifies that several functions that represent sin, cos, tan, LG, and log have a letter priority of 5. return
    p;
}

3. infix to suffix conversion (using the stack implementation conversion)
Infix to Postfix conversion function string Infix_to_uffix (string s) and code implementation and interpretation to solve the following problems
(Divided into various cases, incomplete code):
1. Construct the stack, determine the way of the pressure stack
2. Conversion of Bracket Form
3. Decimal form Conversion
4. Conversion of negative form
5. Conversion of functions with English letters

To achieve a better infix-type conversion suffix, first the input string through the Change function processing:
(For example: input (sin (2) +3) *4, converted to (s2+3) *4, at this time the English alphabet function is similar to the operator, in order to better pressure stack)

String change (String st0) {string St; for (int i = 0; i < st0.size (); i++) {if (priority (st0[i)) = = 1 | | Priority (st0[i]) >=1 &AMP;&A mp Priority (st0[I]) < 5 | | st0[i] = = ' (' | | st0[i] = = ') ' | |
        st0[i] = = '. ')
        {St.push_back (st0[i]);
        else if (st0[i] = = ' s ' && st0[i + 1] = = ' I ') {st.push_back (' s ');
        else if (st0[i] = = ' C ') {st.push_back (' C ');
        else if (st0[i] = = ' t ') {st.push_back (' t ');
        else if (st0[i] = = ' L ' && st0[i + 1] = = ' G ') {St.push_back (' l ');
        else if (st0[i] = = ' L ' && st0[i + 1] = = ' O ') {st.push_back (' o ');
        else if (st0[i] = = ' P ' && st0[i + 1] = = ' I ') {st.push_back (' P '); else if (st0[i) = =' E ') {st.push_back (' e ');
        else if (st0[i] = = ' A ' && st0[i + 1] = = ' B ') {St.push_back (' a ');
    else;
Return St; }

The following is the process of getting into the infix suffix type:

String Infix_to_uffix (string s)
{
    string str0;
    stack< char > mystack;//build a symbol stack
    int mark = 0;//Tag

If the input "2" occurs, precede the "infix string" by adding a 0 to the "0-2" situation.

    if (s[0] = = '-')
    {
        string s0 = "0";
        s = S0 + S;
    }

below for each input:
If the parentheses are negative ("(-2)"), the tag value plus one. And does not operate when read to "-".

if (s[i] = = ' (' && s[i + 1] = = ')
{
    str0.push_back (');
    Str0.push_back ('-');
    Mark + +;
}
else if (s[i] = = '-' && s[i-1] = = ' (');

When the read character is not a closing parenthesis:
(1) When the word identifier the left parenthesis:

if (s[i] = = ' (')
{
    str0.push_back (');
    Mystack.push (' (');
}

(2) When the character is a number and a decimal point

if (priority (s[i)) = = 1 | | | s[i] = = '. '  )
    Str0.push_back (s[i]);

(3) When the character is an operator (including an opening parenthesis)
A. When the symbol stack is empty, direct pressure stack

Str0.push_back (");
if (Mystack.empty ())
    Mystack.push (s[i));

B1. When the entered symbol priority is higher than the symbol stack top symbol priority, it is pressed directly into the symbol stack.

if (priority (s[i)) > Priority (Mystack.top ()))
{
    str0.push_back (")";
    Mystack.push (s[i]);
}

B2. When the input symbol priority equals the symbol stack top symbol priority, the symbol on the top of the stack is released to the suffix string and the input symbol is pressed onto the stack.

if (priority (s[i)) = = Priority (Mystack.top ()))
{
    str0.push_back (mystack.top ());
    Mystack.pop ();
    Str0.push_back (");
    Mystack.push (s[i]);
}

B3. When the entered symbol priority is less than the top of the stack, the symbol in the symbol stack is placed in the suffix string and out of the stack until you meet the "(". If "(" does not exist, the stack is always empty.)

if (priority (s[i)) < priority (Mystack.top ())
{while
    (mystack.size ()!= 0)
    {
        if (mystack.top () = = ' (')  
        str0.push_back (');
        Str0.push_back (Mystack.top ());
        Mystack.pop ();
    }

(4) When the symbol is a closing parenthesis
If the parentheses are in front of a negative form ("(-2)") (IF). Every time the parentheses are matched, the tag value is reduced by one, until zero to determine that there is no left parenthesis representing negative classes on the bottom of the stack.
If the format of the expression (2+3) is in parentheses (else). All the symbols in the stack until the left parenthesis are all out of the stack and put in the suffix string, and delete the "(") in the stack.

If (Mark!= 0)
    mark--;
else
{while
    (Mystack.top ()!= ' (')
    {
        str0.push_back (
        '); Str0.push_back (Mystack.top ());
        Mystack.pop ();
    }
    Mystack.pop ();
}

Enter all symbols in the symbol stack, one at the end of infix, into the suffix string and out of the stack.

while (Mystack.size ()!= 0)
{
    str0.push_back (");
    Str0.push_back (Mystack.top ());
    Mystack.pop ();
}

Finally, return to STR0.

infix type of suffix Test example:
1.
Enter infix type: (Sin (2) +3) *4+5^2
Output suffix: 2 s 3 + 4 * 5 2 ^ +
2.
Input infix type: (cos (3)) ^2+ (sin (3)) ^2
Output suffix: 3 C 2 ^ 3 s 2 ^ +

3. The implementation of the Operation
(1) Defining an operational function (e.g. addition, sin function)

Addition Operation
Void Aadd () 
{
    ans = container.top ();
    Container.pop ();
    Ans + + container.top ();
    Container.pop ();
    Container.push (ans);

Sin Operation
void Ssin ()
{
    ans = sin (container.top ());
    Container.pop ();
    Container.push (ans);

(2) split the string and identify the substring separately and make an action:
The number substring is pressed into the data stack, and the character substring is manipulated to manipulate the data in the data stack.

    String str;
        while (cout<< ">>" && cin >> str) {StringStream SS (Infix_to_uffix (str));
        String sp;  while (SS >> SP)//The suffix expression string is split into substrings and a substring is entered {if (int (sp[0]) > $ && int (sp[
            0] < 58)//When the substring is a number, the number is converted to double to press into the data stack {container.push (Exchange (SP));  else if (sp[0] = = ' && sp.size ()!= 1)//When (-string) format {if int ( sp[1]) > && int (sp[1]) <-Container.push (Exchange (SP
                ) ); }//when string is numeric, convert the number to double to press the data stack else if (sp[1] = = ' P ') {double
                    PI = 3.14159265358979323846264;
                Container.push (-PI);
        }//3.14159265358979323846264 to the data stack if string is-P (sp[1] = = ' E ') {            Container.push (-2.71828182846); }//-2.71828182846 is pressed into the data stack when string is-E (sp[0] = = ' P ') {DOUBL
                E-pi = 3.14159265358979323846264;
            Container.push (PI); }//when the substring is "P", the number "3.1415926535897932384" is pressed into the data stack else if (sp[0] = = ' E ') {Containe
            R.push (2.71828182846);
            }//when the substring is "e", the number "2.71828182846" is pressed into the data stack else if (sp[0] = = ' + ') {aadd ();
            }//when the substring is "+", call the Aadd function (below and so on) else if (sp[0] = = '-") Mminus ();
            else if (sp[0] = = ' * ') mmul ();
            else if (sp[0] = = '/') ddiv ();
            else if (sp[0] = = ' ^ ') ppow ();
            else if (sp[0] = = ' s ') ssin ();
            else if (sp[0] = = ' C ') CCOs ();
     else if (sp[0] = = ' t ')           Ttan ();
            else if (sp[0] = = ' L ') llg ();
            else if (sp[0] = = ' O ') llog ();
            else if (sp[0] = = ' a ') aabs ();
        Else }

4. Output results, and specify accuracy.

if (container.top () > 0 && container.top () < POW (10.0,-8) | | container.top () < 0 && container.t OP () > 0-pow (10.0,-8))
    cout << "Result:"  << 0 << Endl;
else
    printf ("result:%.8g\n", Container.top ());
cout<<endl;

attached: Complete code:

#include <iostream> #include <string> #include <sstream> #include <vector> #include <stack

> #include <cmath> #include <algorithm> #include <iomanip> using namespace std;
stack< double > container;

Double ans;
    The specified priority int priority (char ch) {int p =-3;
    if (int (ch) >= && int (ch) <= | | | ch = = ' E ' | | | ch = = ' P ') p =-1;
    else if (ch = = ' + ' | | | ch = = ') p = 1;
    else if (ch = = ' * ' | | ch = = '/') P = 2;
    else if (ch = = ' ^ ') p = 3;
    else if (ch = = ' s ' | | | ch = = ' c ' | | | ch = = ' t ' | | | ch = ' l ' | | | ch = = ' o ') p = 5;
return p;
    String change (String st0) {string St; for (int i = 0; i < st0.size (); i++) {if (priority (st0[i)) = = 1 | | Priority (st0[i]) >=1 &AMP;&A mp Priority (st0[I]) < 5 | | st0[i] = = ' (' | | st0[i] = = ') ' | |
        st0[i] = = '. ')
        {St.push_back (st0[i]); else if (st0[i] = = ' s ' && st0[i + 1]= = ' I ') {st.push_back (' s ');
        else if (st0[i] = = ' C ') {st.push_back (' C ');
        else if (st0[i] = = ' t ') {st.push_back (' t ');
        else if (st0[i] = = ' L ' && st0[i + 1] = = ' G ') {St.push_back (' l ');
        else if (st0[i] = = ' L ' && st0[i + 1] = = ' O ') {st.push_back (' o ');
        else if (st0[i] = = ' P ' && st0[i + 1] = = ' I ') {st.push_back (' P ');
        else if (st0[i] = = ' E ') {st.push_back (' e ');
        else if (st0[i] = = ' A ' && st0[i + 1] = = ' B ') {St.push_back (' a ');
    else;
Return St;
    }//test infix conversion to suffix string infix_to_uffix (string s) {string str0;
    stack< char > mystack;//build a symbolic stack int mark = 0; if (s[0] = = '-') {
        string s0 = "0";
    s = S0 + S;
    int size = S.size (); for (int i = 0; i < size; i++) {if (s[i] = = ' (' && s[i + 1] = = ') {St
            R0.push_back (");
            Str0.push_back ('-');
        Mark + +;
        else if (s[i] = = '-' && s[i-1] = = ' (');
                    else {if (s[i]!= ') {if (s[i] = = ' (') {
                    Str0.push_back (");
                Mystack.push (' (');  else if (priority (s[i)) = = 1 | | s[i] = = '. '
                )/number and decimal point {str0.push_back (s[i));
                    } else//Symbol {str0.push_back (');
                    if (Mystack.empty ()) Mystack.push (s[i)); else {if (priority (s)[i]) > Priority (Mystack.top ())) {Str0.push_back (")";
                        Mystack.push (s[i]);
                            else if (priority (s[i)) = = Priority (Mystack.top ())) {
                            Str0.push_back (Mystack.top ());
                            Mystack.pop ();
                            Str0.push_back (");
                        Mystack.push (s[i]);  } else//priority is less than stack top element {while (mystack.size ()!= 0
                                {if (mystack.top () = = ' (') break;
                                Str0.push_back (");
                                Str0.push_back (Mystack.top ());
                            Mystack.pop (); } str0.push_back (' ' );
                        Mystack.push (s[i]); }}} else//when s[i]== ') ' {if (ma
                RK!= 0)//judge the parentheses before the negative number {mark--;
                        else {while (Mystack.top ()!= ' (') {
                        Str0.push_back (");
                        Str0.push_back (Mystack.top ());
                    Mystack.pop ();
                } mystack.pop ();
        while (Mystack.size ()!= 0) {str0.push_back (')}}}
        Str0.push_back (Mystack.top ());
    Mystack.pop ();
return STR0;
     //convert string to int double Exchange (string a) {Istringstream SS (a);

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.