以下是使用C++实现后缀表达式求值的示例代码:

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

using namespace std;

// 判断字符是否为操作符
bool isOperator(char c) {
    return (c == '+' || c == '-' || c == '*' || c == '/');
}

// 执行操作符的计算操作
int calculate(int operand1, int operand2, char op) {
    switch(op) {
        case '+':
            return operand1 + operand2;
        case '-':
            return operand1 - operand2;
        case '*':
            return operand1 * operand2;
        case '/':
            return operand1 / operand2;
        default:
            return 0;
    }
}

// 后缀表达式求值函数
int evaluatePostfix(string postfix) {
    stack<int> operandStack; // 操作数栈

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

        if (isspace(c)) {
            continue; // 忽略空格
        } else if (isOperator(c)) {
            // 弹出栈顶的两个操作数
            int operand2 = operandStack.top();
            operandStack.pop();
            int operand1 = operandStack.top();
            operandStack.pop();

            // 计算结果并将结果压栈
            int result = calculate(operand1, operand2, c);
            operandStack.push(result);
        } else {
            // 将操作数字符转换为整数并压栈
            operandStack.push(c - '0');
        }
    }

    // 返回最终结果
    return operandStack.top();
}

int main() {
    string postfix;

    cout << "请输入后缀表达式:";
    getline(cin, postfix);

    int result = evaluatePostfix(postfix);
    cout << "表达式结果为:" << result << endl;

    return 0;
}

上述代码使用了STL中的std::stack来实现操作数栈,同时利用std::string来处理输入的后缀表达式。isOperator函数用于判断字符是否为操作符,calculate函数用于执行操作符的计算操作。evaluatePostfix函数用于求解后缀表达式的结果。

请注意,上述代码假设输入的后缀表达式是有效的,并且只包含+、-、*、/四种运算符,操作数要么是一位整数,要么是多位整数

用c++实现后缀表达式求值要求利用SeqStack类模板实现后缀表达式求值。假设表达式中只包括+、-、、四种运算。分别考虑操作数为一位整数操作数为多位整数的不同情况。输入后缀表达式输出表达式结果。

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

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