C++ 实现数学表达式计算

#include "iostream"
#include "stack"
#include "unordered_map"
#include "vector"

using namespace std;
unordered_map map;
/*自定义错误*/
class MyException:public exception{
public:
    const char * str;
    MyException(const char * obj){
        str=obj;
    }
    const char* what(){
        return str;
    }
};

/*运算符优先级*/
void initMap() {
    map['+'] = 0;
    map['-'] = 0;
    map['*'] = 1;
    map['/'] = 1;
    map['!'] = 2;
    map['^'] = 2;
}

/*阶乘*/
int factorial(int a){
    if(a==1||a==0)return 1;
    return a*factorial(a-1);
}

vector cutString(string s, char x) {
    vector STRS;

    for (int i = 0;s[i] != '\0';) {
        string str;
        while (s[i] != x) {
            str += s[i];
            i++;
        }
        STRS.push_back(str);
        i++;
    }
    return STRS;
}
/*转换成后缀表达式*/
string change(char* s) {
    char* p = s;
    string str;
    stack st = stack();
    while (*p != '\0') {
        if (*p >= '0' && *p <= '9') {
            str += *p;
            while (*(p + 1) >= '0' && *(p + 1) <= '9'||*(p+1)=='.') {
                p++;
                str += *p;
            }
            str += " ";
        }
        else if (*p == '(') {
            st.push(*p);
        }
        else if (*p == ')') {
            while (st.top() != '(') {
                str += st.top();
                str += " ";
                st.pop();
                if(st.empty()){
                    throw MyException("左括号缺失") ;
                }
            }
            st.pop();
        }
        else if(*p=='+'||*p=='-'||*p=='*'||*p=='/'||*p=='!'||*p=='^'){
            if ((p==s || *(p-1) == '(')&&*p=='-') {
                    str+="0";
                    str+=" ";
                    st.push(*p);
            }
            else if (st.empty() || st.top() == '(') {
                st.push(*p);
            }
            else {
                while (map[*p] <= map[st.top()]) {
                    str += st.top();
                    str += " ";
                    st.pop();
                    if (st.empty() || st.top() == '(') {
                        break;
                    }
                }
                st.push(*p);
            }
        }
        else {
            throw MyException("算式错误");
        }
        p++;
    }
    while (!st.empty()) {
        if (st.top() == '(') {
            throw MyException("右括号缺失");
        }
        str += st.top();
        str += " ";
        st.pop();
    }
    return str;
}

/*把字符串转换float*/
float STR_TO_FLOAT(const string& s) {
    float sum1= 0,sum2=0;
    int i = 0;
    int j = s.length() - 1;
    for (i = 0;s[i] != '.'&&i<=j;i++) {
        sum1 *= 10;
        sum1 += s[i] - '0';
    }
    if (i<=j) {
        for (;j!=i;j--) {
            sum2 *= 0.1;
            sum2 += s[j] - '0';
        }
        sum2 *= 0.1;
    }

    return sum1+sum2;
}

/*计算表达式*/
float calculate(char* s) {
    string str = change(s);
    vector STRS = cutString(str, ' ');
    stack stack;

    for (auto x : STRS) {
        if (x[0] >= '0' && x[0] <= '9') {
            stack.push(STR_TO_FLOAT(x));
        }
        else {
            if(x[0]=='!'){
                float first=stack.top();
                stack.pop();
                if((int)first!=first)throw MyException("阶乘错误");
                first= factorial((int)first);
                stack.push(first);
            }
            else{
                if(stack.empty())throw MyException("算式错误");
                float second = stack.top();
                stack.pop();
                if(stack.empty())throw MyException("算式错误");
                float first = stack.top();
                stack.pop();
                switch (x[0]) {
                    case '+':
                        first += second;
                        break;
                    case '-':
                        first -= second;
                        break;
                    case '*':
                        first *= second;
                        break;
                    case '/':
                        first /= second;
                        break;
                    case '^':
                        first=pow(first,second);
                        break;
                }
                stack.push(first);
            }

        }
    }
    return stack.top();
}

利用栈stack就算表达式

int main() {
    initMap();//初始化运算符优先级

    cout<<"输入exit退出"<> s;
        if (s[0]=='e')break;
        try{cout << calculate(s) << endl;}
        catch(MyException & e) {
            cout<

C++ 实现数学表达式计算_第1张图片

你可能感兴趣的:(c++,开发语言,算法,数据结构)