四则表达式计算(stl stack, 不带注释)

#include 
#include 
#include 
using namespace std;

stack opStack;
stack numStack;
char exp[205], postExp[205];


void trans(char* exp, char* postExp) {
    char ch;
    int i = 1, j = 0;
    ch = exp[0];
    while(ch != 0) {
        switch(ch) {
        case '(':
            opStack.push(ch);
            break;
        case ')':
            while(opStack.top() != '(') {
                postExp[j++] = opStack.top();
                opStack.pop();
            }
            opStack.pop();
            break;
        case '+':
        case '-':
            while(!opStack.empty() && opStack.top() != '(') {
                postExp[j++] = opStack.top();
                opStack.pop();
            }
            opStack.push(ch);
            break;
        case '*':
        case '/':
            while(!opStack.empty() && opStack.top() != '('
                    && (opStack.top() == '*' || opStack.top() == '/') ) {
                    postExp[j++] = opStack.top();
                    opStack.pop();
            }
            opStack.push(ch);
            break;
        default:
            while(ch >= '0' && ch <= '9') {
                postExp[j++] = ch;
                ch = exp[i++];
            }
            i --;
            postExp[j++] = ' ';
        }
        ch = exp[i++];
    }
    while(!opStack.empty()) {
        postExp[j++] = opStack.top();
        opStack.pop();
    }
    postExp[j] = 0;
}
double calC(char* exp) {
    double tmp;
    char ch = postExp[0];
    int i = 1;
    double a, b;
    while(ch != 0) {
        if(ch >= '0' && ch <= '9') {
            tmp = 0;
            while(ch >= '0' && ch <= '9') {
                tmp = 10 * tmp + ch - '0';
                ch = postExp[i++];
            }
            numStack.push(tmp);
        }
        else {
            b = numStack.top(), numStack.pop();
            a = numStack.top(), numStack.pop();
            switch(ch){
            case '+':
                numStack.push(a + b);
                break;
            case '-':
                numStack.push(a - b);
                break;
            case '*':
                numStack.push(a * b);
                break;
            case '/':
                numStack.push(a / b);
                break;
            default:
                break;
            }
        }
        ch = postExp[i++];
    }
    return numStack.top();
}
int main() {

    double ans = 0;
    cin >> exp;
    trans(exp, postExp);
  //  cout << postExp << endl;
    ans = calC(postExp);
    printf("%.2f\n", ans);
    return 0;
}

测试数据:
3+(12/(2*2+1))
5.40

你可能感兴趣的:(未分类)