C++实现中缀表达式求值

本程序使用C++语言实现了一个中缀表达式求值程序,支持以下功能:

  • 支持加减乘除、幂运算和括号。
  • 操作数为正整数,但可能不止一位,不超过10位。
  • 运算结果为整数,值域为[-2^31, 2^31)。
  • 除法运算结果若为小数则进行截尾取整。
  • 若除法运算中除数为0,则输出'INVALID'。
  • 幂运算须自行实现,不允许调用pow等系统函数。

代码:

#include <iostream>
#include <string>
#include <stack>
#include <cmath>

int getPriority(char op) {
    if (op == '+' || op == '-')
        return 1;
    else if (op == '*' || op == '/')
        return 2;
    else if (op == '^')
        return 3;
    else
        return 0;
}

int calculate(int a, int b, char op) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            if (b == 0)
                throw 'INVALID';
            return a / b;
        case '^':
            int result = 1;
            for (int i = 0; i < b; i++) {
                result *= a;
            }
            return result;
        default:
            return 0;
    }
}

int evaluateExpression(const std::string& expression) {
    std::stack<int> operands;
    std::stack<char> operators;

    for (int i = 0; i < expression.length(); i++) {
        char c = expression[i];

        if (c == ' ')
            continue;
        else if (isdigit(c)) {
            int operand = 0;
            while (i < expression.length() && isdigit(expression[i])) {
                operand = operand * 10 + (expression[i] - '0');
                i++;
            }
            operands.push(operand);
            i--;
        } else if (c == '(') {
            operators.push(c);
        } else if (c == ')') {
            while (!operators.empty() && operators.top() != '(') {
                int operand2 = operands.top();
                operands.pop();
                int operand1 = operands.top();
                operands.pop();
                char op = operators.top();
                operators.pop();
                int result = calculate(operand1, operand2, op);
                operands.push(result);
            }
            operators.pop();  // 弹出左括号
        } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
            while (!operators.empty() && getPriority(operators.top()) >= getPriority(c)) {
                int operand2 = operands.top();
                operands.pop();
                int operand1 = operands.top();
                operands.pop();
                char op = operators.top();
                operators.pop();
                int result = calculate(operand1, operand2, op);
                operands.push(result);
            }
            operators.push(c);
        }
    }

    while (!operators.empty()) {
        int operand2 = operands.top();
        operands.pop();
        int operand1 = operands.top();
        operands.pop();
        char op = operators.top();
        operators.pop();
        int result = calculate(operand1, operand2, op);
        operands.push(result);
    }

    return operands.top();
}

int main() {
    std::string expression;

    while (getline(std::cin, expression) && !expression.empty()) {
        try {
            int result = evaluateExpression(expression);
            std::cout << result << std::endl;
        } catch (const char* error) {
            std::cout << error << std::endl;
        }
    }

    return 0;
}

使用方法:

输入多行中缀表达式,每行一个,以空行结束。程序将计算每个表达式的值并输出结果。

示例:

输入:

5+(10*2)-6
8*(999+1)
1+5/(1-1)
7*2^3

输出:

19
8000
INVALID
56

注意:

  • 代码中的除法运算符/执行的是整数除法,结果会被截断。
  • 如果表达式中出现除数为0的情况,程序会抛出'INVALID'异常并输出。
  • 幂运算通过循环实现,没有使用库函数pow
  • 程序假设输入的表达式是合法的,不会对输入进行额外的校验。

希望这个程序对你有所帮助!

C++实现中缀表达式求值 - 支持幂运算和错误处理

原文地址: https://www.cveoy.top/t/topic/izH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录