题目1101:计算表达式[RE]

题目描述:

对于一个不存在括号的表达式进行计算

输入:

存在多种数据,每组数据一行,表达式不存在空格

输出:

输出结果

样例输入:
6/2+3+3*4
样例输出:
18

代码:

#include <stdio.h>
#include <stack>
using namespace std;
stack<double> in;
stack<int> op;
char str[100];
int p[][5] = {
    1,0,0,0,0,
    1,0,0,0,0,
    1,0,0,0,0,
    1,1,1,0,0,
    1,1,1,0,0,
};
void getOp(bool &retop, int &retnum, int &i) {
    if(i==0 && op.empty()) {
        retop = true;
        retnum = 0;
        return;
    }
    if(str[i]==0) {
        retop = true;
        retnum = 0;
        return;
    }
    if(str[i]>='0' && str[i]<='9')
        retop = false;
    else {
        retop = true;
        if(str[i]=='+')
            retnum = 1;
        else if(str[i]=='-')
            retnum = 2;
        else if(str[i]=='*')
            retnum = 3;
        else
            retnum = 4;
        i++;
        return;
    }
    retnum = 0;
    while(str[i]>='0'&&str[i]<='9') {
        retnum *= 10;
        retnum += str[i] - '0';
        i++;
    }
    return;
}

int main() {
    while(gets(str)) {
        bool retop;
        int retnum;
        int index = 0;
        while(!in.empty()) in.pop();
        while(!op.empty()) op.pop();
        while(true) {
            double tmp;
            getOp(retop,retnum,index);
            if(retop==false)
                in.push((double)retnum);
            else {
                if(op.empty() || p[retnum][op.top()]==1)
                    op.push(retnum);
                else {
                    while(p[retnum][op.top()]==0) {
                        int ret = op.top();
                        op.pop();
                        double b = in.top();
                        in.pop();
                        double a = in.top();
                        in.pop();
                        if(ret == 1)
                            tmp = a + b;
                        else if(ret == 2)
                            tmp = a - b;
                        else if(ret == 3)
                            tmp = a * b;
                        else 
                            tmp = a / b;
                        in.push(tmp);
                    }
                    op.push(retnum);
                }
            }
            if(op.size()==2 && op.top()==0)
                break;
        }
        int ans = (int) in.top();
        printf("%d\n",ans);
        
    }
    return 0;
}
                        

在自己机器上测试结果正确。但是提交时:Runtime Error.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值