c++ - 计算简单数学表达式的函数的实现。(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”值不存在。会出现一些我没想到的额外爆裂声。
解决方案
减法运算的操作数被交换。这是因为当您处理+
and-
操作的堆栈时,您正在从右到左解析等式。
在您的示例中,当-
在堆栈中找到时,result
是12
. 你弹出-
,然后减去6
,6
结果应该是-6
。
你应该使用
result = stod(result_stack.top()) - result;
减法。
您的代码中也没有错误检查无效方程式。
推荐阅读
- java - 如何在 Spring Boot 中从 swagger 中删除 Authentication 参数?
- javascript - Vue js watcher 对更改没有反应
- robotframework - 如何使用机器人框架上传文件?
- ios - 在调用 viewDidDisappear 之后修改视图是不好的做法吗?
- c++ - OPENCL 警告:不兼容的指针类型将 'float __global[16]' 传递给 '__global float4 * 类型的参数
- kotlin - 等价于 if(root == null) return root; 在科特林
- python - 循环遍历子小部件并将小部件值(条目和复选按钮)存储在列表中
- python - Whatsapp 使用 Python 聊天分析器,下一步是什么?
- awk - 删除换行符,同时保持换行符后跟另一个换行符
- vba - 导出 PowerPoint 幻灯片