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;
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的C++代码,可以计算基本的数学表达式,包括加、减、乘、除、括号等。 ```c++ #include <iostream> #include <stack> #include <string> using namespace std; // 判断运算符优先级 int priority(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { return 0; } } // 计算两个数的运算结果 double calculate(double num1, double num2, char op) { double result; switch (op) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: break; } return result; } // 计算表达式的值 double evaluate(string expression) { stack<double> numStack; stack<char> opStack; int len = expression.length(); for (int i = 0; i < len; i++) { if (expression[i] >= '0' && expression[i] <= '9') { // 如果是数字,将其入栈 double num = 0; while (i < len && expression[i] >= '0' && expression[i] <= '9') { num = num * 10 + (expression[i] - '0'); i++; } i--; numStack.push(num); } else if (expression[i] == '(') { // 如果是左括号,将其入栈 opStack.push(expression[i]); } else if (expression[i] == ')') { // 如果是右括号,计算括号内的表达式的值 while (!opStack.empty() && opStack.top() != '(') { double num2 = numStack.top(); numStack.pop(); double num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); double result = calculate(num1, num2, op); numStack.push(result); } opStack.pop(); // 弹出左括号 } else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') { while (!opStack.empty() && priority(opStack.top()) >= priority(expression[i])) { double num2 = numStack.top(); numStack.pop(); double num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); double result = calculate(num1, num2, op); numStack.push(result); } opStack.push(expression[i]); } } while (!opStack.empty()) { double num2 = numStack.top(); numStack.pop(); double num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); double result = calculate(num1, num2, op); numStack.push(result); } return numStack.top(); } int main() { string expression; cout << "请输入表达式:"; cin >> expression; double result = evaluate(expression); cout << "表达式的值为:" << result << endl; return 0; } ``` 该代码使用两个栈,一个存储数字,一个存储运算符。遍历表达式,如果是数字,则将其入数字栈;如果是运算符,则将其与运算符栈顶的元素进行比较,如果其优先级较高,则将其入栈;否则,弹出运算符栈顶的元素,弹出数字栈中的两个元素,计算它们的运算结果,将结果入数字栈。最后,数字栈中剩余的元素即为表达式的值。 注意,该代码只能处理基本的数学表达式,如果表达式中包含函数、变量、复杂的运算符优先级等,需要使用更复杂算法计算

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值