HDU1237简单计算器(栈的应用)

HDU1237简单计算器 

#include <bits/stdc++.h>
using namespace std;       
stack<double>q1;
stack<char>q2;  
string line;
void Calculate(){
    double t1 = q1.top();   q1.pop();
    double t2 = q1.top();   q1.pop();
    char t = q2.top();    q2.pop();
    switch(t){
        case '+':q1.push(t2+t1);break;
        case '-':q1.push(t2-t1);break;
        case '*':q1.push(t2*t1);break;
        case '/':q1.push(t2/t1);break;
    }
}
int Precede(char x,char y){
    if(x == '+' || x == '-'){
        if(y == '*' || y == '/' || y == '(')   return -1;
        return 1;
    }else if(x == '*' || x == '/'){
        if(y == '(')    return -1;
        else return 1;
    }else if(x == '('){
        if(y == ')')    return 0;
        else return -1;
    }else if(x == '#'){
        if(y == '#')    return 0;
        else return -1;
    }else if(x == ')')  return 1;
}
int main(){
   while(getline(cin,line) && line != "0"){
        while(!q1.empty())  q1.pop();
        while(!q2.empty())  q2.pop();
        q2.push('#');
        line += "#";    //终结符
        int i = 0;
        while(line[i] != '#' || q2.top() != '#'){
            if(isspace(line[i]))    i++;
            else if(isdigit(line[i])){   //如果输入的是数字
                double num = 0;
                while(isdigit(line[i]))
                    num = num * 10 + (line[i++] - '0');
                q1.push(num);
            }else{
                int flag = Precede(q2.top(),line[i]);
                if(flag == -1)  q2.push(line[i]),   i++;   //栈顶优先级低
                else if(flag == 0)  q2.pop(),   i++;   //脱去括号
                else    Calculate();    //不需要i++,下一轮循环继续和前面比较
            }
        }
        printf("%.2f\n",q1.top());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值