wsh_wshkk 2023-06-25 10:59 采纳率: 70%
浏览 16
已结题

c++前缀求值补全代码的问题

img


怎么用这个图片上的代码块补全代码啊,就是前缀求值,前缀表达式

  • 写回答

3条回答 默认 最新

  • MarkHan_ 2023-06-25 11:12
    关注
    
    #include <iostream>
    #include <vector>
    #include <sstream>
    
    int evaluatePrefixExpression(std::vector<std::string>& tokens, int& index) {
        std::string token = tokens[index];
    
        if (isOperator(token)) {
            int operand1 = evaluatePrefixExpression(tokens, ++index);
            int operand2 = evaluatePrefixExpression(tokens, ++index);
    
            if (token == "+")
                return operand1 + operand2;
            else if (token == "-")
                return operand1 - operand2;
            else if (token == "*")
                return operand1 * operand2;
            else if (token == "/")
                return operand1 / operand2;
        }
        else {
            // Convert the token to an integer
            std::stringstream ss(token);
            int operand;
            ss >> operand;
            return operand;
        }
    
        return 0; // Default return value (should not reach here if the input is valid)
    }
    
    int evaluatePrefixExpression(std::vector<std::string>& tokens) {
        int index = 0;
        return evaluatePrefixExpression(tokens, index);
    }
    
    int main() {
        std::vector<std::string> tokens = { "*", "+", "2", "3", "4" };
        int result = evaluatePrefixExpression(tokens);
        std::cout << "Result: " << result << std::endl;
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 10月27日
  • 已采纳回答 10月19日
  • 创建了问题 6月25日