簡體   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