C++實現 逆波蘭表達式計算問題
#include <iostream> #include <string> using namespace std; class Stack { private: int size; int top; float *listArray; public: Stack(int sz=20); ~Stack(); bool push(float it);//入棧 bool pop(float& it);//出棧 bool isEmpty();//判斷棧是否為空 bool isOne();//判斷棧里是否一個元素 }; Stack::Stack(int sz) //棧構造函數 { size=sz; top=0; listArray=new float[size]; } bool Stack::push(float it) { if(top==size) return false; listArray[top++]=it; return true; } bool Stack::pop(float& it) { if(top==0) return false; it=listArray[--top]; return true; } bool Stack::isEmpty() //判斷站是否為空 { if(top==0) return true; return false; } bool Stack::isOne() { if(top==1) return true; return false; } Stack::~Stack() { delete listArray; } //此函數傳進輸入的字符串,並對字符串進//行掃描並進行相應處理,得到結果(函數聲//明) void compute(char* str); int main() { char str[20]; cin.getline(str,20,'#'); compute(str); return 0; } //此函數傳進輸入的字符串,並對字符串進//行掃描並進行相應處理,得到結果(函數體) void compute(char* str) { Stack aStack; float x=0,y=0,s1,s2,temp; int i; i=0; while(str[i]) { switch(str[i]) { case '+': //加法運算 if(aStack.isOne()||aStack.isEmpty()) { cout << "表達式不符合要求"; return; } aStack.pop(s1); aStack.pop(s2); x=s2+s1; aStack.push(x); x=0;i++;break; case '-': //減法運算 if(aStack.isOne()||aStack.isEmpty()) { cout << "表達式不符合要求"; return; } aStack.pop(s1); aStack.pop(s2); x=s2-s1; aStack.push(x); x=0; i++; break; case '*': //乘法運算 if(aStack.isOne()||aStack.isEmpty()) { cout << "表達式不符合要求"; return; } aStack.pop(s1); aStack.pop(s2); x=s2*s1; aStack.push(x); x=0; i++; break; case '/': //除法運算 if(aStack.isOne()||aStack.isEmpty()) { cout << "表達式不符合要求"; return; } aStack.pop(s1); aStack.pop(s2); if(s1==0) { cout << "分母為0!" << endl; return; } x=s2/s1; aStack.push(x); x=0; i++; break; case ' ': //如果是空格,將數據x押入棧中 if(str[i-1]>=48&&str[i-1]<=57) aStack.push(x); x=0; i++; y=0; break; case '.': //獲得小數部分 temp=10.0; while(str[++i]!=' ') { if(str[i]>=48&&str[i]<=57) y=y+(str[i]-48)/temp; temp*=10; } x+=y; break; default: //將字符數字轉換為浮點型的數字 if(str[i]>=48&&str[i]<=57) { x=x*10+str[i]-48; i++; } } } //判斷棧是否只有切僅有一個元素,是就輸//出結果 if(aStack.isOne()) { aStack.pop(x); cout << str << '=' << x << endl; } }