首页 > 解决方案 > 计算简单数学表达式的函数的实现。(C++)

问题描述

我正在尝试编写一个评估简单数学表达式的函数(只有四个操作)。我使用堆栈和向量来做到这一点。但是堆栈操作的行为并不像我预期的那样。我找不到原因。我对不同的解决方案持开放态度。

该函数应采用如下字符串:

“5 * 44 + 3 / 2 * 4 - 12”

并将结果作为双精度返回。

#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cstdlib>

using namespace std;

vector<string> split(const std::string& str, char delim = ' ')
{
    vector<string> elements;
    stringstream ss(str);
    string token;
    while (getline(ss, token, delim)) {
        elements.push_back(token);
    }

    return elements;
}


double evaluate(string operation)
{
    vector<string> values = split(operation, ' ');
    stack<string> result_stack;
    double result = 0;

    for(unsigned int i = 0; i < values.size(); i++){
        if(values[i] == "*"){
            double mini_result = stod(result_stack.top()) * stod(values[i+1]);
            result_stack.pop();
            i++;
            result_stack.push(to_string(mini_result));
        }
        else if(values[i] == "/"){
            double mini_result = stod(result_stack.top()) / stod(values[i+1]);
            result_stack.pop();
            i++;
            result_stack.push(to_string(mini_result));
        }
        else{
            result_stack.push(values[i]);
        }
    }

    for(unsigned int i = 0; i<result_stack.size(); i++){
        if(result_stack.top() == "-"){
            result_stack.pop();
            result = stod(result_stack.top()) - result;
            result_stack.pop();
        }
        else if(result_stack.top() == "+"){
            result_stack.pop();
            result += stod(result_stack.top());
            result_stack.pop();
        }
        else{
            result += stod(result_stack.top());
            result_stack.pop();
        }
    }

    return result;

}




int main()
{

    cout<<evaluate("5 * 44 + 3 / 2 * 4 - 12");
}

在第二个 for 循环之前,result_stack 中的值对于这个例子应该是这样的。“12 | - | 6 | + | 220”。并且返回值应该是 214。

但在第二个 for 循环之前,堆栈仅包含“12 | - | 6”值。“+”和“220”值不存在。会出现一些我没想到的额外爆裂声。

对于这个例子,堆栈内容应该是这样的

标签: c++functionmathexpressionevaluate

解决方案


减法运算的操作数被交换。这是因为当您处理+and-操作的堆栈时,您正在从右到左解析等式。

在您的示例中,当-在堆栈中找到时,result12. 你弹出-,然后减去66结果应该是-6

你应该使用

result = stod(result_stack.top()) - result;

减法。

您的代码中也没有错误检查无效方程式。


推荐阅读