利用栈实现四则运算

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int caculate(int a,int b,char sign);
void destack_two(stack<int> &s1,stack<char> &s2);
int level(char ch);
int main()
{
    stack<int>s1;
    stack<char>s2;
    int count=0,n;
    char str[100];
    cin>>str;
    n=strlen(str);
    for(int i=0; i<n; i++)
    {
        if(str[i]=='#')//前面和后面的#的不同做法。
        {
            if(count==0)
            {
                s2.push(str[i]);
                count++;//告诉编译器它下次遇到的将是后面的#
            }
            else
            {
                while(s1.size()!=1)
                {
                    destack_two(s1,s2);
                }
                cout<<s1.top()<<endl;
            }
        }
        else if(48<=str[i]&&str[i]<=57)
        {
            if(48<=str[i-1]&&str[i-1]<=57)
            {
                int temp = s1.top() * 10 + (str[i] - '0');//注意一下这里
                s1.pop();
                s1.push(temp);
            }
            else
            {
               s1.push(str[i]-'0');
            }
        }
        else if(str[i]=='(')s2.push(str[i]);
        else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
        {
            //要在()也形成一种和外面一样的规则,所以下面会有相关对()的操作。
            if( level( str[i]) > level(s2.top() )||s2.top()=='(')
            {
                s2.push(str[i]);
            }
            else if(level(str[i]) <= level(s2.top())&&s2.top()!='(')
            {
                destack_two(s1,s2);//把上一个优先级高的字符计算
                s2.push(str[i]);//再把现在的加入进去
            }
        }
        else if(str[i]==')')
        {
            while(s2.top()!='(')
            {
                destack_two(s1,s2);
            }
            s2.pop();
        }
    }
    return 0;
}
int caculate(int a,int b,char sign) //计算函数
{
    switch(sign)
    {
    case '+':
        return a+b;
    case '-':
        return a-b;
    case '*':
        return a*b;
    case '/':
        return a/b;
    default:
        cout<<"操作错误"<<endl;
        break;
    }
    return 0;
}

void destack_two(stack<int>&s1,stack<char>&s2)//进行遍历的
{
    int a,b;
    char ch;
    a=s1.top();
    s1.pop();
    b=s1.top();
    s1.pop();
    ch=s2.top();
    s2.pop();
    s1.push(caculate(a,b,ch));
}
int level(char ch)//给优先级定位。
{
    switch(ch)
    {
    case'(':
        return 5;
    case')':
        return 5;
    case'*':
        return 3;
    case'/':
        return 3;
    case'+':
        return 2;
    case'-':
        return 2;
    case'#':
        return 1;
    default:
        cout<<"错误输入"<<endl;
        break;
    }
    return 0;
}

小结:

1.当代码多的时候注意main()对应的return 0要放好,我好几次都放在for里面。。。。

2,敲代码一定一定得严谨啊,真的要一个一个计较。。。。

3,这个是借鉴了同学的代码。。。。。。

猜你喜欢

转载自blog.csdn.net/qq_40554649/article/details/79980325