C++ 后缀评估问题
c++ postfix evaluation problems
stack<int> s;
int main() {
string exp;
cout << "Enter postfix expression: ";
getline(cin, exp);
int calc = evaluatePosfix(exp);
cout << calc << endl;
}
int evaluatePosfix(string exp) {
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == ' ' || exp[i] == ',') {
continue;
}
if (isNum(exp[i])){
int operand = 0;
while(i < exp.length() && isNum(exp[i])) {
operand = (operand*10) + (exp[i] - '0');
i++;
}
i--;
cout << operand << "&&" << endl;
s.push(operand);
}
else if(isOperator(exp[i])) {
int operand2 = s.top(); s.pop();
int operand1 = s.top(); s.pop();
int result = performOperation(operand1, operand2, exp[i]);
s.push(result);
}
//cout << s.top() << " $$$" << endl;
}
return s.top();
}
bool isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return true;
}
return false;
}
bool isNum(char c) {
if (c >= '0' || c <= '9') {
return true;
}
return false;
}
int performOperation(int operand1, int operand2, char operation) {
if (operation == '+') {
return operand1 + operand2;
}
else if (operation == '-') {
return operand1 + operand2;
}
else if (operation == '*') {
return operand1 * operand2;
}
else if (operation == '/') {
return operand1 / operand2;
}
else {
cout << "Error" << endl;
return -1;
}
}
未正确评估修复后。当我输入 22+ 时,它返回 215 而不是 4。当程序检测到运算符时,它应该弹出堆栈中的 2 个元素,但由于某种原因它没有这样做。调用 performOperation 时,不会发生该操作,因此不会将任何内容推送到堆栈上。
如果22+
应该计算到4
那么本节是罪魁祸首:
while(i < exp.length() && isNum(exp[i])) {
operand = (operand*10) + (exp[i] - '0');
i++;
}
编写代码是为了处理大于 10 的数字,但您的示例建议你仅支持个位数。
@meat是正确的,您需要将输入流(文件或 cin(作为标记读取。
#include <cstring>
char token[6];
while (stream >> token)
{
if (token[0] == '=') // what ever the end char is
{
//process and evaluate expression
}
else if (isdigit(*token)) // will pass a 4 byte int not just 0-9
{
// process a number
}
else if (ispunct(token0])) // is 1 byte math symbol + - * /
{
// process a math symbol
}
这应该可以解决0-9的阅读问题。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- std::condition_variable::wait()如何评估给定的谓词
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 亚马逊在线评估编码问题,以找到第n个几何级数
- C++ 后缀评估问题
- C++11重新评估参考问题