栈实现简单计算器的四则运算(STL)

来源:互联网 发布:淘宝干货贴吧 编辑:程序博客网 时间:2024/05/29 08:56
#include <bits/stdc++.h>using namespace std;stack<char>st;stack<double>cal;char s[1200],post[1200];double res;//中缀转后缀void trans(){    while(!st.empty())        st.pop();    int i=0,j=0;    char ch;    while(s[i]){        ch=s[i];        if(s[i]=='(')            st.push(s[i]);        else if(ch==')')        {            while(!st.empty()&&st.top()!='(')            {                post[j++]=st.top();                post[j++]=' ';                st.pop();            }            st.pop();        }        else if(ch=='+'||ch=='-')        {            while(!st.empty()&&st.top()!='(')            {                post[j++]=st.top();                post[j++]=' ';                st.pop();            }            st.push(ch);        }        else if(ch=='*'||ch=='/')        {            while(!st.empty()&&st.top()!='('&&(st.top()!='+')&&(st.top()!='-'))            {                post[j++]=st.top();                post[j++]=' ';                st.pop();            }            st.push(ch);        }        else        {            while(ch>='0'&&ch<='9')            {                post[j++]=ch;                i++;                if(s[i]) ch=s[i];                else break;            }            post[j++]=' ';            i--;        }        i++;    }    while(!st.empty())    {        post[j++]=st.top();        post[j++]=' ';        st.pop();    }    j--;    post[j]='\0';}//输出后缀表达式的值void work(char *s){    double n1,n2;    double d=0;    int i=0;    while(!cal.empty())    {        cal.pop();    }    int len=strlen(post);    while(i<len)    {        if(s[i]>='0'&&s[i]<='9')        {            d=0;            while(s[i]>='0'&&s[i]<='9')            {                d=d*10+(s[i]-48);                i++;            }            cal.push(d);        }        else if(s[i]=='+')        {            n2=cal.top();            cal.pop();            n1=cal.top();            cal.pop();            cal.push(n1+n2);        }        else if(s[i]=='-')        {            n2=cal.top();            cal.pop();            n1=cal.top();            cal.pop();            cal.push(n1-n2);        }        else if(s[i]=='*')        {            n2=cal.top();            cal.pop();            n1=cal.top();            cal.pop();            cal.push(n1*n2);        }        else if(s[i]=='/')        {            n2=cal.top();            cal.pop();            n1=cal.top();            cal.pop();            cal.push(n1/n2);        }        i++;    }    cout<<cal.top()<<endl;}int main(){    while(gets(s)!=NULL)    {        trans();        //输出后缀表达式        puts(post);        //输出结果        work(post);    }    return 0;}

0 0
原创粉丝点击