BJFUOJ-

基于栈的后缀算术表达式求值

#include<iostream>
#include<cstring>
#include <iomanip>
using namespace std;
#define maxsize 100


template<typename T>
struct stack {
    T data[maxsize];
    int top;
    stack() :top(-1) {};
    bool Empty() {
        if (top == -1) return true;
        else return false;
    }
    bool Push(T x) {
        if (top == maxsize - 1) return false;
        data[++top] = x;
        return true;
    }
    double Pop() {
        return data[top--];
    }
    bool getTop(T& x) {
        if (top == -1) return false;
        x = data[top];
        return true;
    }
};


double cal(double a, char c, double b) {
    switch (c)
    {
        case '+':return a + b; break;
        case '-':return a - b; break;
        case '*':return a * b; break;
        case '/':return a / b; break;
        default:
            return 0;
            break;
    }
}

double PostfixCal(char exp[]) {
    int len = strlen(exp);
    stack<double>s; //数字栈
    //后缀表达式求值,只需要一个数字栈,运算符的先后顺序已经确定好了
    for (int i = 0; i < len; i++) {
        if (exp[i] >= '0' && exp[i] <= '9') {
            s.Push(exp[i] - '0');
        }
        else if (exp[i] == ' ') {
            //lue
        }
        else if (exp[i] == '=') {
            break;
        }
        else {
            double a = 0;
            double b = 0;
            if (!s.Empty()) {
                a = s.Pop();
            }
            if (!s.Empty()) {
                b = s.Pop();
            }
            double x = cal(b, exp[i], a);
            s.Push(x);
        }
    }
    double res;
    s.getTop(res);
    return res;
}


int main() {

    char str[100];
    while (cin.getline(str, 100)) {
        if (strcmp(str, "=") == 0) {
            break;
        }
        cout <<fixed<<setprecision(2)<< PostfixCal(str)<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值