0
#include <iostream>
#include <string>
#include <stack>
#include <sstream>

using namespace std;

stack<int>aStack;
stack<int>operand1;
stack<int>operand2;
stringstream postfix;

stringstream &postfixExp(string ch)
{
  for(int i =0; i< ch.length(); i++)
  {
      if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
      {
          aStack.push(ch[i]);
      }

      else if(ch[i] == '+')
      {
        operand1.push(aStack.top());
        aStack.pop();

        operand2.push(aStack.top());
        aStack.pop();

        int x = operand1.top() - 48;
        int y = operand2.top() - 48;
        int result = x + y;

        aStack.push(result);
      }

      else if(ch[i] == '*')
      {
        operand1.push(aStack.top());
        aStack.pop();

        operand2.push(aStack.top());
        aStack.pop();

        int x = operand1.top() - 48;
        int y = operand2.top() - 48;
        int result = x * y;

        aStack.push(result);
      }
  }


  postfix << aStack.top();
  return postfix;

}


int main()
{
  string postfix = "32+2*";

  stringstream * result = &postfixExp(postfix);
  cout << result-> str() ;

  return 0;
}

嗨,有人知道我上面的代码有什么问题吗?我的程序应该返回一个后缀符号的值。我输入“32+2*”作为后缀符号,它应该返回 10。显然出了点问题,它返回 -86

我想错误来自这个特定的代码

else if(ch[i] == '*')
      {
        operand1.push(aStack.top());
        aStack.pop();

        operand2.push(aStack.top());
        aStack.pop();

        int x = operand1.top() - 48;
        int y = operand2.top() - 48;
        int result = x * y;

        aStack.push(result);
      }

从那里,我显示了操作数 2,它显示 -43 而不是 7(源自之前添加的“34+”)

请让我知道哪一部分错了,为什么我的操作数 2 的值不是 7。

谢谢

4

3 回答 3

2

在将字符推送到堆栈之前将它们转换为整数。在我看来,你的编译器应该已经警告你了。尝试调高警告级别。

aStack.push(ch[i]);

变成

aStack.push(ch[i] - '0'); // '0' is 48

另请注意,您可以使用isdigitfrom<cctype>而不是ch[i]手动比较每个数字。

于 2013-09-24T03:13:13.860 回答
2
  if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
  {
      aStack.push(ch[i]);
  }

这应该是:

  if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
  {
      aStack.push(ch[i] - '0');
  }

摆脱其他- 48的,因为他们坏了。

于 2013-09-24T03:23:32.100 回答
0

问题如下

  else if(ch[i] == '+')
  {
    operand1.push(aStack.top());
    aStack.pop();

    operand2.push(aStack.top());
    aStack.pop();

    int x = operand1.top() - 48;
    int y = operand2.top() - 48;
    int result = x + y;

    aStack.push(result + 48);
   }

这将使它成为 10。您还需要更改第二个 aStack.push(result)。

于 2013-09-24T03:14:43.153 回答