标签:
#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; }
标签:
原文地址:http://www.cnblogs.com/fkissx/p/4767081.html