问题 5169 --口算练习

5169: 口算练习★★★

时间限制: 1 Sec  内存限制: 128 MB
提交: 29  解决: 24
[提交][状态][命题人:]

题目描述

小明爸爸在写一个计算口算练习题的程序,式子中包含+-*/四种运算,参与运算的数均为非负整数,式子中可能含有括号。


#include <bits/stdc++.h>
using namespace std;
char s[110];
int n;
stack<int> num;
stack<char> op;
int cal(int x,int y,char z)
{
    if (z=='+')
        return x+y;
    else if(z=='-')
        return x-y;
    else if(z=='*')
        return x*y;
    return x/y;
}
int main() 
{
    cin>>s;
    n=strlen(s);
    int i=0;
    while(i<n)
    {
        if(s[i]>='0' &&s[i]<='9')
        {
            int t=0;
            while(i<n&&s[i]>='0' &&s[i]<='9')
            {
                ______(1)________;
                i++;
            }
            num.push(t);
        }
        else
        {
            if (s[i]=='(')
                op.push(s[i]);
            else if(_____(2)________)
            {
                char ch=op.top();
                while(ch!='(')
                {
                    int a=num.top(); 
                    num.pop();
                    int b=num.top();
                    num.pop();
                    int c=cal(b,a,ch);
                    num.push(c);
                    op.pop();
                    if(op.empty()) break;
                    ch=op.top();
                }
                _______(3)________;
            }
            else
            {
                if(!op.empty())
                {
                    char ch=op.top();
                    while(_____(4)________)
                    {
                        int a=num.top(); 
                        num.pop();
                        int b=num.top();
                        num.pop();
                        int c=cal(b,a,ch);
                        num.push(c);
                        op.pop();
                        if(op.empty()) break;
                        ch=op.top();
                    }
                }
                ______(5)_________;
            }
            i++;
        }
    }
    cout<<______(6)________;
    return 0;
}

输入

输入一行长度不超过100的式子,中间不含空格。

输出

输出计算得到的答案。
样例输入
Copy
13-(2+1)*2+7=
样例输出
Copy
14

提示

来源

[提交][状态]