计祘客 栈 加减乘除

#include<cstdio>
#include<stack>
#include<map>
#include<cmath>
#include<iostream>
#include<cstring>
using namespace std;
const int elength=30;
int ans=0;
stack<int>s1;
stack<char>s2;

void Caculate()
{
            char t;
            int t1,t2;
                t=s2.top();
                s2.pop();
                t1=s1.top();
                s1.pop();
                t2=s1.top();
                s1.pop();
                //cout<<"t1£º"<<t1<<" "<<t2<<endl;
                if(t=='*')
                {
                    ans=t1*t2;
                   s1.push(ans);
                }
                if(t=='^')
                {
                    ans=pow(t2,t1);
                    s1.push(ans);
                }
                if(t=='+')
                {
                    ans=t1+t2;
                    //cout<<t1<<" "<<t2<<endl;
                    s1.push(ans);
                }
                if(t=='-')
                {
                    ans=t2-t1;
                    s1.push(ans);
                }
                if(t=='/')
                {
                    ans=t2/t1;
                    s1.push(ans);
                }
}

int main()
{
    map<char,int> m;
    char c[elength];
    //memset(c,0,sizeof(c));
    int temp;
\\定义运算符的优先级
    m['+']=1;
    m['-']=1;
    m['*']=2;
    m['/']=2;
    m['^']=3;
    //stringstream ss;
    //getline(cin,c);
    //ss<<c;
    //while(ss>>r)
    cin>>c;
    int i=0;
    int cnt=0;
    int ii;
    while(1)
    {
        temp=0;
        ii=0;
        for(;c[i]-'0'>=0&&c[i]-'0'<=9;i++)
        {
            s1.push(c[i]-'0');
        }
        cnt++;//记录栈内应该有多少个元素
        while(s1.size()>=cnt)
        {
            //cout<<"top"<<s1.top()<<endl;
            temp=temp+s1.top()*pow(10,ii++);
            s1.pop();//将数字字符合成数字
        }
        //cout<<"temp:"<<temp<<endl;
        s1.push(temp);
        if(c[i]=='\0') break;
        if(s2.empty()||m[c[i]]>m[s2.top()])
            s2.push(c[i]);
        else
        {
            while(!s2.empty())
            {
                Caculate();
                cnt=1;//完成一次计算后栈内只有一个元素
            }

            s2.push(c[i]);
        }
        i++;
    }
        while(!s2.empty())
        Caculate();
        ans=s1.top();
    cout<<ans<<endl;
}

首先设立两个栈,一个存放数字,一个存放字符串(加减乘除乘方),然后分别入栈。

当即将入栈的符号的运算级大于栈顶的运算级,直接入栈。如果即将入栈的符号运算级小于等于栈顶,则先把栈内的式子先出栈计算,注意的是数字字符转换成数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值