现在的位置: 首页 > 综合 > 正文

hdu 1237 简单计算器(表达式求值)

2013年02月02日 ⁄ 综合 ⁄ 共 1678字 ⁄ 字号 评论关闭

我用栈写,一个栈保存符号,一个栈保存数字。

有个技巧是再添加一个结束符'#'.然后根据优先级来进行计算即可。

如果有括号的话再加一个优先级比较的数组即可。

至于优先级,首先是普通认知的优先级,然后相同优先级前者的大于后者。

左括号小于任何,又括号大于任何。

#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <cstdio>
using namespace std;

stack<double> OPN;//restore the num
stack<char> OPO;//restore the operation
/*
1 is prior
0 is equal
-1 is lower
*/
int op[200][200];
void init(){
    while(!OPN.empty())
        OPN.pop();
    while(!OPO.empty())
        OPO.pop();
    OPO.push('#');
    op['+']['+']=1;op['+']['-']=1;op['+']['*']=-1;op['+']['/']=-1;

    op['-']['+']=1;op['-']['-']=1;op['-']['*']=-1;op['-']['/']=-1;

    op['*']['+']=1;op['*']['-']=1;op['*']['*']=1; op['*']['/']=1;

    op['/']['+']=1;op['/']['-']=1;op['/']['*']=1; op['/']['/']=1;

    op['+']['#']=1;op['-']['#']=1;op['*']['#']=1; op['/']['#']=1;

    op['#']['+']=-1;op['#']['-']=-1;op['#']['*']=-1; op['#']['/']=-1;
}
bool in(char c){
    if(c=='+'||c=='-'||c=='*'||c=='/'||c=='#'||c==' ')
        return true;
    return false;
}
double operate(double s1,double s2,char opp){
    switch(opp){
        case '+':
            return s1+s2;
        case '-':
            return s1-s2;
        case '*':
            return s1*s2;
        case '/':
            return s1/s2;
    }
    return 0;
}
int main(){
    char str[250];
    while(gets(str)){
        init();
        double s=0;
        int len=strlen(str);
        if(str[0]=='0'&&len==1)
            return 0;
        str[len]='#';
        str[len+1]='\0';
       // puts(str);
        int i=0;
        bool f=0;
        while(str[i]!='#'||OPO.top()!='#'){
            if(str[i]==' ') { i++;continue;}
            while(!in(str[i])){
                f=1;
                s=s*10+(str[i]-'0');
                //printf("%lf\n",s);
                i++;
            }
            if(f){
                OPN.push(s);
                s=0;
                f=0;
                continue;
            }
            char t_op=OPO.top();
            if(op[(int)t_op][(int)str[i]]==1){
                double _s=OPN.top();
                OPN.pop();
                double s_=OPN.top();
                OPN.pop();
               // printf("%lf %lf \n",_s,s_);
                double temp=operate(s_,_s,t_op);
                OPN.push(temp);
                OPO.pop();
              //  OPO.push(str[i]);
            }
            else if(op[(int)t_op][(int)str[i]]==-1){
                OPO.push(str[i]);
                i++;
            }
        }
        double ans=OPN.top();
        printf("%.2lf\n",ans);
    }
    return 0;
}

抱歉!评论已关闭.