表达式计算

输入表达式计算出值

#include <iostream>
#include <stack>
#include <algorithm>
#include <cmath>

using namespace std;

stack<int> nums;
stack<char> ops;

void cal()
{
    int a = nums.top();
    nums.pop();
    int b = nums.top();
    nums.pop();
    char c = ops.top();
    ops.pop();
    int d = 0;

    if (c == '+')
        d = b + a;
    else if (c == '-')
        d = b - a;
    else if (c == '*')
        d = b * a;
    else if (c == '/')
        d = b / a;
    else
        d = pow(b, a); // ^
    nums.push(d);
}

int main()
{
    string str;
    cin >> str;

    string left;
    for (int i = 0; i < str.size(); i++)
        left += '(';
    str = left + str + ')';

    for (int i = 0; i < str.size(); i++)
    {
        if (isdigit(str[i]))
        {
            int j = i, t = 0;
            while (isdigit(str[j]))
            {
                t = t * 10 + str[j] - '0';
                j++;
            }
            nums.push(t);
            i = j - 1;
        }
        else
        {
            char c = str[i];
            if (c == '(')
                ops.push(c);
            else if (c == '+' || c == '-')
            {
                if (c == '-' && i && !(isdigit(str[i - 1])) && str[i - 1] != ')')
                {
                    int j = i + 1, t = 0;
                    while (isdigit(str[j]))
                    {
                        t = t * 10 + str[j] - '0';
                        j++;
                    }
                    nums.push(-t);
                    i = j - 1;
                }
                else
                {
                    while (ops.top() != '(')
                        cal();
                    ops.push(c);
                }
            }
            else if (c == '*' || c == '/')
            {
                while (ops.top() == '*' || ops.top() == '/' || ops.top() == '^')
                    cal();
                ops.push(c);
            }
            else if (c == '^')
            {
                while (ops.top() == '^')
                    cal();
                ops.push(c);
            }
            else if (c == ')')
            {
                while (ops.top() != '(')
                    cal();
                ops.pop();
            }
            else
                cout << "invalid operator!" << endl;
        }
    }

    cout << nums.top() << endl;
    return 0;
}
追求吾之所爱
原文地址:https://www.cnblogs.com/rstz/p/14390993.html