c++ - c++ 后缀求值问题
问题描述
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 的数字而编写的,但您的示例表明您只支持单个数字。
推荐阅读
- java - 在java中使用SqlBuilder创建动态查询
- c# - 投掷硬币,直到一侧连续下降 3 次
- javascript - 如何使用 officejs api 在 MS Word 中重新加载页眉和页脚
- python-3.x - 如何使用 IQR 从 DataFrame 中删除异常值?
- java - java代码为什么println 10?
- css - flex-direction:Safari 中的列
- reactjs - React PropType 检查动态对象
- javascript - 在动态生成的 div 上应用 touchstart
- scala - Scala 中 DSE Cassandra 上的 Spark SQL 查询
- ember.js - 如何减少 Windows 10 上的 ember 应用程序构建时间,但它在 ubuntu 上运行良好