2016-04-21 103 views
0

下面我試圖編寫一個評估後綴表達式的程序。但是,我注意到,我設置的兩個要素未被設置爲正確的值。我仍然在學習C++庫中的堆棧特性,所以如果有人能解釋爲什麼會發生這種情況,我將不勝感激!評價後綴函數

/*Sample output: 
Enter an infix or prefix expression:3+4-1 
Postfix is: 34+1- 
postFix[i]: 3 
postFix[i]: 4 
element1: 52 
element2: 51 
val is: 103 
postFix[i]: 1 
element1: 49 
element2: 103 
val is: 54 
Value is 54*/ 

int evaluatePostfix (string postFix) 
{ 
    stack<int> operands; 

     int length = postFix.length(); 
     int val = 0; 
     for (int i = 0; i < length; i++) 
     { 
       //if the char is a digit push the digit onto the stack 
       if(isdigit(postFix[i])) 
       { 
         operands.push(postFix[i]); 
         cout << "postFix[i]: " << postFix[i] << endl; 
       } 
       else if (isOperator(postFix[i])) 
       { 
         // 
         //element 1 and element 2 will be the element on the top of the stack 
         // 
         int element1 = operands.top(); 
         cout << "element1: " << element1 << endl; 
         operands.pop(); 
         int element2 = operands.top(); 
         cout << "element2: " << element2 << endl; 
         operands.pop(); 
         // 
         //create a switch statement that evaluates the elements based on the operator 
         // 
         switch(postFix[i]) 
         { 
           case '+': 
             val = element2 + element1; 
             cout << "val is: " << val << endl; 
             operands.push(val); 
             break; 
           case '-': 
             val = element2 - element1; 
             cout << "val is: " << val << endl; 
             operands.push(val); 
             break; 
           case '*': 
             val = element2 * element1; 
             operands.push(val); 
             break; 
           case '/': 
             val = element2/element1; 
             operands.push(val); 
             break; 
           default: 
             return 0; 
         } 

                       } 

     } 
     return val; 
} 
+0

你能給一個堅實的例子嗎?例如,我推3,但它彈出42. – ChiefTwoPencils

+0

我認爲這是這裏的問題。我將這些元素放在堆棧上,但是我推入堆棧的元素並不是被彈出的元素。因此,例如,我按3和4.然後,程序看到操作符'+',並決定彈出頂部的兩個元素,它們應該是3和4,但它會彈出52和51等隨機數。我不知道它爲什麼這樣做 –

回答

0

的問題是你的後綴是一個字符串,當你把這些字符(這是有效的整數),你得到的ascii值回(例如51,52)。那些對應於正確的數字(例如3,4)

你最終得到的是一個偏移48的值,它對應於0符號。

+0

我仍然在學習ascii值,我還沒有完全理解它們是如何工作的。我如何適應這個? –

+0

一個簡單的解決方案,因爲如果48知道偏移量,則從堆棧返回的內容中或在您推入它之前將其減去48 .. 51 - 48 = 3和52 - 48 = 4,依此類推。 @ChynnaHernandez – ChiefTwoPencils

+0

謝謝您的解釋 –