2012-09-10 94 views
0

是我的評價後綴評價後綴評估算法

#include<iostream> 
#include<string> 
using namespace std; 
template<class T> 
class Stack 
{ 
private: 
    T *s;int N; 
public: 
    Stack(int maxn) 
    { 
     s=new T[maxn]; 
     N=0; 
    } 
    int empty()const 
    { 
    return N==0; 
    } 
    void push(T k) 
    { 
     s[N++]=k; 
    } 
    T pop() 
    { 
     return s[--N]; 
    } 
    }; 

int main() 
    { 
     //postfix evaluation 
     char *a="3+4*5"; 
     int N=strlen(a); 
     Stack<int>save(N); 
     for(int i=0;i<N;i++) 
     { 
      if(a[i]=='+') 
       save.push(save.pop()+save.pop()); 
      if(a[i]=='*') 
       save.push(save.pop()*save.pop()); 
      if((a[i]>='0' && a[i]<='9')) 
       save.push(0); 
      while((a[i]>='0' && a[i]<='9')) 
       save.push(10*save.pop()+(a[i++]-'0')); 
        } 
     cout<<save.pop()<<" "<<endl; 
    return 0; 
} 

嘗試,但不是答案23,因爲4 * 5 + 3 = 23,它給了我回答5個,我的理解,這個代碼給了我這個結果是因爲,首先它檢查是否有+標記爲i = 0,不是,然後檢查它是否是*,這也不是,所以它先推0,然後計算10 * 0 +'3' - '0',等於3,(它會被推入棧中),對於i = 1,a [i]等於3,所以它打印3+,第二個彈出窗口是未定義的,所以我認爲它是錯誤,請幫我修復它

+3

'3 + 4 * 5'是綴,而不是postfix的(作爲後綴表達式將是'3 4 5 * +')。如果你想讓你的輸入使用中綴表示法,你必須先轉換它,然後才能評估它爲後綴表達式(例如使用[shunting-yard算法](http://en.wikipedia.org/wiki/Shunting -yard_algorithm))。 –

+0

當我更改爲postfix時,它會評估類似-3300的東西,爲什麼? –

+0

這個數字正好-33685674 –

回答

1

這適用於一點修復:

#include <iostream> 
#include <cstring> 

using namespace std; 

template<class T> 
class Stack 
{ 
private: 
    T *s; 
    int N; 

public: 
    Stack(int maxn) 
    { 
     s = new T[maxn]; 
     N = 0; 
    } 
    int empty()const 
    { 
     return N == 0; 
    } 
    void push(T k) 
    { 
     s[N++] = k; 
    } 
    T pop() 
    { 
     return s[--N]; 
    } 
}; 

int main() 
{ 
    //postfix evaluation 
    const char *a = "3 4 5*+"; 
    int N = strlen(a); 

    Stack<int>save(N); 

    for (int i = 0; i < N; i++) 
    { 
     if (a[i]=='+') 
      save.push(save.pop() + save.pop()); 

     if (a[i]=='*') 
      save.push(save.pop() * save.pop()); 

     if (a[i] >= '0' && a[i] <= '9') 
     { 
      save.push(0); 
      while (a[i] >= '0' && a[i] <= '9') 
       save.push(10 * save.pop() + a[i++] - '0'); 
      i--; 
     } 
    } 

    cout << save.pop() << " " << endl; 

    return 0; 
} 

輸出(ideone):

23 

現在,如果你刪除i--;我補充說,該代碼將在a[]因爲增量爲2的i跳躍的字符,在a[i++]for (int i = 0; i < N; i++)

i--;沒有輸出(ideone):

9 
+0

如果我們不把表達式放在表達式中的話,該怎麼辦? –

+0

仔細查看代碼。如果這不能解決您的問題,請嘗試運行該程序。 –

+0

沒有它回答,只是我沒有把表達,如此表達,而陳述 –