计算器表达式求值实现

实现对包括加减乘除及括号表达式的求值。使用两个栈来实现,一个栈存放数,一个存放运算符。程序运行时,如果读入是数字则直接入栈,如果是运算符则根据优先级来处理。

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

char gInputString[1000];

//+ - * / ( ) #
char opt_priority[7][8] = {
">><<<>>",
">><<<>>",
">>>><>>",
">>>><>>",
"<<<<<=>",
">>>>>>>",
"<<<<<<="
};

int getIdx(char c) {
    switch(c) {
        case '+': return 0;
        case '-': return 1;
        case '*': return 2;
        case '/': return 3;
        case '(': return 4;
        case ')': return 5;
        case '#': return 6;
    }
}

int Operate(int a, char opt, int b) {
    switch(opt) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
    }
}


int getExpressionValue() {
    int a, b, len, num, pos = 0;
    char c, opt;
    stack<char> sOpt;
    stack<int> sNum;
    sOpt.push('#');
    len = strlen(gInputString);
    gInputString[len++] = '#';
    c = gInputString[pos++];
    while(c != '#' || sOpt.top() != '#') {
        //如果是数字,直接放入数字栈中
        if(isalpha(c)) {
            num = 0;
            while(isalpha(c)) {
                num = num * 10 + c - 'A';
                c = gInputString[pos++];
            }
            sNum.push(num);
        }else {//如果是运算符
            switch(opt_priority[getIdx(sOpt.top())][getIdx(c)]) {
                case '<': //栈顶元素优先级低
                    sOpt.push(c); 
                    c = gInputString[pos++];
                    break;
                case '=': //脱掉括号
                    sOpt.pop();
                    c = gInputString[pos++];
                    break;
                case '>': //退栈并将运算结果入栈
                    opt = sOpt.top(); sOpt.pop();
                    b = sNum.top(); sNum.pop();
                    a = sNum.top(); sNum.pop();
                    sNum.push(Operate(a, opt, b));
                    break;
            }
        }
    }
    return sNum.top();
}


int main() {
//    freopen("c:/aaa.txt", "r", stdin);
    while(gets(gInputString) ) {
        printf("%d\n", getExpressionValue());
    }
    return 0;
}

 

posted on 2014-06-28 19:47  CrazyAC  阅读(303)  评论(0编辑  收藏  举报