我正在尝试用 C++ 编写一个函数来评估后缀符号方程。我的一般策略是扫描一个字符串(以正确的格式,例如“10 20 + 30 -”)。
我通过增加索引变量 i 来做到这一点。在每次递增时,我都会检查字符是数字、运算符还是两者都不是。如果是数字,我使用 getNextNum() 函数获取所有后续数字,将其转换为浮点数,然后将其推送到堆栈中。我还将 i 增加捕获的数字的长度。如果字符是运算符,我会获取堆栈的顶部两个元素,执行操作,然后将结果推回堆栈。
问题是,我的 while 循环似乎只经过一次。该函数仅返回字符串中的第一个数字。我不知道出了什么问题,我将不胜感激!我在 while 循环中插入了 cout 语句,并且 i 仅在第一个数字之后递增到索引。
编辑:好的,我添加了 getNextNum() 函数。此外,我用 strLength 的 cout 更新了 evalPostfix(),以及在 while 循环的每次迭代之后更新了 i。运行给定的代码时,我得到这个:
Running…
Please enter an expression in postfix notation: 555 666+
3
555
3
Your expression evaluates to: 555
似乎 strLength 被设置为小于应有的值。为什么会这样?
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <stack>
using namespace std;
string getNextNum(string equation, int i);
float evalPostfix(string postfix);
float doOperation(float x, float y, char op);
float doOperation(float x, float y, char op)
{
switch (op) {
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
default:
return 0.0;
}
}
string getNextNum(string equation, int i)
{
string num = "";
const string DELIM = "+-*/%^ ";
while (i<equation.length()) {
// Iterate through equation until you hit a delimiter.
if (DELIM.find(equation[i]) != -1) {
break;
}
num += equation[i];
i++;
}
return num;
}
float evalPostfix(string postfix)
{
const string OPS = "+-*/%^";
const string NUMS = "0123456789";
int strLength = postfix.length();
stack<float> numStack;
int i = 0;
cout << strLength << endl;
while (i<strLength) {
if (NUMS.find(postfix[i]) != -1) {
// If a character is a digit, then you should get the
// value and push it to the stack (could be multiple characters long).
string sNextNum = getNextNum(postfix, i);
float fNextNum = atof(sNextNum.c_str());
numStack.push(fNextNum);
cout << sNextNum << endl;
i += (sNextNum.length() - 1);
}
else if (OPS.find(postfix[i] != -1)) {
// Otherwise, pop the top two elements of the stack, perform the
// operation, then push the result back to the stack.
char op = postfix[i];
float x = numStack.top();
numStack.pop();
float y = numStack.top();
numStack.pop();
float z = doOperation(x, y, op);
numStack.push(z);
}
i++;
cout << i << endl;
};
// Once the entire string has been scanned through, there should be a float
// left in the stack, simply return that.
return numStack.top();
}
int main ()
{
cout << "Please enter an expression in postfix notation: ";
string postfix;
cin >> postfix;
float eval = evalPostfix(postfix);
cout << "Your expression evaluates to: " << eval;
return 0;
}