1

我正在尝试用 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;
}
4

2 回答 2

1

您有一些问题,其中一个主要问题是拼写错误,您放错)了位置:

else if (OPS.find( postfix[i] != -1 ) ) {
                 ^                  ^ 

应该:

else if (OPS.find( postfix[i] ) != std::string::npos) {
                 ^            ^  

所以你正在比较charat 位置i-1然后find对布尔结果进行 a 。接下来你应该使用-1来比较find但是std::string::npos

正如乔纳森所指出的:

cin >> postfix ;

只能读到第一个黑色或换行符。使用getline将解决该问题:

if (getline(cin, postfix))
于 2013-07-07T02:33:50.557 回答
0

一个主要问题是输入cin >> postfix;语句只读取第一个单词。回显输入以确保程序看到您认为它正在看到的内容。

Shafik Yaghmour指出了另一个问题

学习要点:

  1. 回显输入以确保程序看到您认为它看到的内容;
  2. 使用合适的打印消息跟踪关键变量;
  3. post SSCCE ( Short, Self-Contained, Correct Example ) — 可以编译的代码;
  4. 发布示例输入和您从中获得的输出。

此代码适用于输入555 666+

#include <iostream>
#include <string>
#include <stack>
using namespace std;

static float doOperation(float x, float y, char op)
{
    cout << "doOp: x = " << x << ", y = " << y << ", op = " << op << endl;
    if (op == '+')
        x += y;
    return x;
}

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;
    while (i<strLength) {
        cout << "Top - i: " << i << ", strLength: " << strLength << endl;
        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 << "End - i: " << i << ", strLength: " << strLength << endl;
    }
    cout << "After - i: " << i << ", strLength: " << strLength << 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;
    if (getline(cin, postfix))
    {
        cout << "Evaluating: " << postfix << endl;
        float eval = evalPostfix(postfix);
        cout << "Your expression evaluates to: " << eval << endl;
    }
    return 0;
}

样本跟踪:

Please enter an expression in postfix notation: 555 666+
Evaluating: 555 666+
Top - i: 0, strLength: 8
555
End - i: 3, strLength: 8
Top - i: 3, strLength: 8
End - i: 4, strLength: 8
Top - i: 4, strLength: 8
666
End - i: 7, strLength: 8
Top - i: 7, strLength: 8
doOp: x = 666, y = 555, op = +
End - i: 8, strLength: 8
After - i: 8, strLength: 8
Your expression evaluates to: 1221

显然,一旦解决了您要解决的特定问题,您可能会丢失大部分诊断输出,但是准备按照所示的方式添加它可以大大加快解决它的过程。

于 2013-07-07T02:36:30.273 回答