PAT linear structure 3. Application of value stack for prefix expression

Source: Internet
Author: User

Topic Links:

Prefix expression evaluation




Exercises

Evaluation ideas with suffix expressions:

Encountered the value of the stack, encountered the operator from the stack to remove the top two values to operate, then the results into the stack, the final stack of the top element is the answer.

The prefix expression is traversed from the back forward.




Code:

#include <iostream> #include <cstdio> #include <cstring> #include <stack>using namespace std; int op (char a) {if (a== ' + ' | | a== '-' | | a== ' * ' | |    a== '/') return 1; return 0;}    int main () {char str1[105];    int len,i,flag=0,k=1,flagg=0;    Double s=0;    Gets (STR1);    Len=strlen (STR1);     stack<double>q; for (i=len-1; i>=0; i--)//from backwards {if (str1[i]== ') {if (s!=0) Q.pu               SH (s);                   flag=0,s=0,k=1;        } else if (flag==0&&str1[i]>= ' 0 ' &&str1[i]<= ' 9 ') flag=1,s=str1[i]-' 0 ', k=k*10;        else if (flag==1&&str1[i]>= ' 0 ' &&str1[i]<= ' 9 ') s=s+ (str1[i]-' 0 ') *k,k=k*10;         else if (flag==1&&str1[i]== '-') s=-s;            else if (flag==1&&str1[i]== '. ')        s=s/100.0,k=1;            else if (Flag==0&&op (Str1[i])) {double A,b,ans;            A=q.top (); Q.Pop ();            B=q.top ();            Q.pop ();            if (str1[i]== ' + ') ans=a+b;            else if (str1[i]== '-') ans=a-b;            else if (str1[i]== ' * ') ans=a*b; else if (str1[i]== '/') {if (b==0)//divisor is 0 is error flagg=1                    ;                ans=a/b;        } q.push (ANS);    }} if (Q.empty ())//Last set of sample Q.push (s); if (flagg==1| |    Q.size () >1) printf ("error\n");    else printf ("%.1lf\n", Q.top ()); return 0;}



PAT linear structure 3. Application of value stack for prefix expression

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.