標籤:
#include<iostream>#include<cstdlib>#include<cctype>using namespace std;template<class T>class stack{private: T* base; T* top; int stackSize;public: stack(int a=100):stackSize(a) { base=top=new T[stackSize]; } ~stack() { delete [] base; base=top=NULL; cout<<"stack析構\n"; } bool is_empty()const; bool is_full()const; bool pop(T &a); bool push(T a); int len()const;};template<class T>bool stack<T>::is_empty()const{ if(base==top) return true; else return false;}template<class T>bool stack<T>::is_full()const{ if(top-base==stackSize) return true; else return false;}template<class T>bool stack<T>::push(T a){ if(!is_full()) { *(top++)=a; return true; } else return false;; }template<class T>bool stack<T>::pop(T& a){ if(!is_empty()) { a=*(--top); return true; } else return false;}template<class T>int stack<T>::len()const{ cout<<(int*)base<<endl; cout<<(int*)top<<endl; return top-base;}int main(){ char c; stack<double>s; char bluff[10]; int i=0; printf("輸入逆波蘭運算式,元素之間用空格分開,並以#結束\n"); scanf("%c",&c); while(c!=‘#‘) { while(isdigit(c) || c==‘.‘)//處理的數是double型的 { bluff[i++]=c;// 用一塊緩衝區儲存char型資料後轉換 if(i>=10) { printf("\n輸入的數過大\n"); return 1; } scanf("%c",&c); if(‘ ‘==c) // 處理數字後的空格,符號後的空格不管 { bluff[i]=‘\0‘; i=0; s.push(atof(bluff)); break; } } if(‘+‘==c || ‘-‘==c || ‘*‘==c || ‘/‘==c) { double d,e; s.pop(d); s.pop(e); switch(c) { case ‘+‘: s.push(d+e); break; case ‘-‘: s.push(e-d);// 後出的減去前出的 break; case ‘*‘: s.push(e*d); break; case ‘/‘: if(d !=0) s.push(e/d); else { printf("\n除數不能為0\n"); return 1; } break; default: printf("\n符號不能識別\n"); return 1; } } scanf("%c",&c); } double ans; s.pop(ans); printf("\n計算結果是%f\n",ans); return 0;}
逆波蘭運算式計算(尾碼運算式)