繁体   English   中英

中缀后缀转换C ++,似乎无法获得正确的答案

[英]infix postfix conversion c++, can't seem to get the right answer

因此,我正在为分配给使用运算符的堆栈将中缀格式转换为后缀格式的赋值进行操作,对于中缀符号的数字,该代码可以正常工作,但对于运算符,它不起作用,因为该堆栈最初是启动时为空,因此它无法进入while循环,但是我不知道如何解决此逻辑错误。

void calculator::convertInputIntoPostfix(){
  stack S;
  for(int i=0;i<mInfixInput.length();i++){
    if(mInfixInput[i]>='0' && mInfixInput[i]<='9'){
      mPostfixOutput+=mInfixInput[i];
    }
    else if(isOperator(mInfixInput[i])){                                                                                     
    while
    (!S.isEmpty()
    &&hasHigherPrecedenceThan(S.top(),mInfixInput[i])==true){
        mPostfixOutput += S.top();
        S.pop();
    }
    S.push(mInfixInput[i]);
    }
  }
  while(!S.isEmpty()){
    mPostfixOutput += S.top();
    S.pop();
 }                                                                                                                                                             
}

bool calculator::isOperator(int c) const
{
  return ((c == '+') ||
          (c == '-') ||
          (c == '*') ||
          (c == '/') ||
          (c == '^'));
}
bool calculator::hasHigherPrecedenceThan(int aLHS, int aRHS) const
{
  if ((aRHS == '+' || aRHS == '-') &&
      (aLHS == '*' || aLHS == '/' || aLHS == '^')) {
    return true;
  }
  if ((aRHS == '+' || aRHS == '-' || aRHS == '*' || aRHS == '/') &&
      (aLHS == '^')) {
    return true;
  }
  if (aLHS == '^' && aRHS == '^') {
    return true;
  }
  return false;
}

上面没有给出的大小写(例如()和逗号)可以忽略,而infix是通过main中的输入获取的。 该堆栈是一个链表堆栈。 该值为整数。 我得到的2 + 3 * 3 * 3(期望的答案:233 * 3 * +)的输出是2333 ** +,因为它甚至没有进入我编写的while循环,它只是存储值放入堆栈,最后输出。

2333**+可能是意外的,但实际上并没有错,只是错误地关联了。

计算优先级的方式是,告诉算法aRHS == '*' && aLHS == '*'false ,即运算符不是左关联的。 它是。 对于 ^ 以外的所有其他所有等于运算符的情况,同上。当右关联时,您会错误地使左关联。

在此算法中确定优先顺序时,通常使用表而不是if-else链,并根据优先顺序测试> =,而不是>。

Wikipedia中给出的Dijkstra Shunting-yard算法的版本具有以下条件,而不是您的条件:

while ((there is a function at the top of the operator stack)
    or (there is an operator at the top of the operator stack with greater precedence)
    or (the operator at the top of the operator stack has equal precedence and is left associative))
    and (the operator at the top of the operator stack is not a left bracket):
        pop operators from the operator stack onto the output queue.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM