自学内容网 自学内容网

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

本文使用C++实现Shunting-yard算法,将中缀表达式转换为后缀表达式,然后使用后缀表达式计算结果,实现了目前支持以下

  • 四则运算(+、-、*、/)
  • 开平方(^)
  • 取基数为 10 的对数(L)
  • 小括号

的组合,实现代码如下

#include <iostream>  
#include <stack>  
#include <string>  
#include <vector>  
#include <cctype>
#include <math.h>

 /**
 * @brief getPrecedence 判断优先级
 * @param op 操作符
 * @return 0是特殊的,最高优先级,其他的数字越大,优先级越高
 */
int getPrecedence(char op) {
    if (op == '+' || op == '-') {
        return 1;
    }
    else if (op == '*' || op == '/') {
        return 2;
    }
    else if (op == '^')
    {
        return 3;
    }
    else {
        return 0;
    }
}

 /**
 * @brief isOperator 判断字符是否是运算符
 * @param c
 * @return 是返回true
 */
bool isOperator(char c) {
    return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}

/**
 * @brief shuntingYard Shunting-yard 算法
 *  用于将中缀表达式(如 "3 + 4 * 2")转换为后缀表达式(逆波兰表示法,如 "3 4 2 * +")的算法
 * @param expression 中缀表达式
 * @return 后缀表达式
 */
std::vector<std::string> shuntingYard(const std::string& expression) {
    std::stack<std::string> operators;
    std::vector<std::string> output;

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

        if (std::isspace(c)) {
            continue; // Skip whitespace  
        }
        else if (isdigit(c) || (c == '.' && (i == 0 || !isdigit(expression[i - 1])))) {
            std::string number;
            while (i < expression.length() && (isdigit(expression[i]) || expression[i] == '.')) {
                number += expression[i++];
            }
            output.push_back(number);
            --i; // Because the for loop also increments i  
        }
        else if (isOperator(c)) {
            while (!operators.empty() && getPrecedence(c) <= getPrecedence(operators.top()[0])) {
                output.push_back(operators.top());
                operators.pop();
            }
            operators.push(std::string(1, c));
        }
        else if (c == '(') {
            operators.push("(");
        }
        else if (c == ')') {
            while (!operators.empty() && operators.top() != "(") {
                output.push_back(operators.top());
                operators.pop();
            }
            if (!operators.empty()) {
                operators.pop(); // Remove the '(' from the stack  
            }
        }
        else if (c == 'L')
        {
            operators.push("L");
        }
        else {
            std::cerr << "Error: Unexpected character '" << c << "'" << std::endl;
            return {};
        }
    }

    // Push any remaining operators to the output  
    while (!operators.empty()) {
        output.push_back(operators.top());
        operators.pop();
    }

    return output;
}

/**
 * @brief evaluatePostfix 计算后缀表达式的结果
 * @param postfix 后缀表达式
 * @return 计算结果
 */
double evaluatePostfix(const std::vector<std::string>& postfix) {
    std::stack<double> values;

    for (const std::string& token : postfix) {
        if (isOperator(token[0])) {
            double val2 = values.top(); values.pop();
            // 防止表达式中有负数导致程序崩溃
            double val1 = 0.0;
            if (values.size() > 0)
            {
                val1 = values.top();
                values.pop();
            }
            double result;
            switch (token[0]) {
            case '+': result = val1 + val2; break;
            case '-': result = val1 - val2; break;
            case '*': result = val1 * val2; break;
            case '/':
                if (val2 == 0) throw std::invalid_argument("Division by zero");
                result = val1 / val2; break;
            case '^': result = pow(val1, val2); break;
            default: throw std::invalid_argument("Invalid operator");
            }
            // 显示计算过程
            std::cout << val1 << token[0] << val2 << "=" << result << std::endl;
            values.push(result);
        }
        else if (token[0] == 'L')
        {
            double val = values.top(); values.pop();
            double result = log10(val);
            values.push(result);
            std::cout << "Log10(" << val << ")=" << result << std::endl;
        }
        else {
            values.push(std::stod(token));
        }
    }

    return values.top();
}

int main() {
    std::string infix;
    std::cout << "Enter an infix expression: ";
    std::getline(std::cin, infix);

    while (infix.size() > 0)
    {
        try
        {
            std::vector<std::string> postfix = shuntingYard(infix);

            // 打印后缀表达式用于验证  
            std::cout << "Postfix expression: ";
            for (const auto& token : postfix) {
                std::cout << token << " ";
            }
            std::cout << std::endl;

            double result = evaluatePostfix(postfix);
            std::cout << "Result: " << result << std::endl;
        }
        catch (const std::exception& e) {
            std::cerr << "Error: " << e.what() << std::endl;
        }
        infix = "";
        std::cout << "Enter an infix expression: ";
        std::getline(std::cin, infix);
    }
    

    return 0;
}


原文地址:https://blog.csdn.net/qq_28742901/article/details/136377444

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!