棧實現簡易計算器

計算數學表達式的值。 輸入數學表達式,輸出表達式的計算結果。數學表達式由單個數字和運算符+、-、、/、(、)構成,
例如 2+3
(4+5)–6/4。

#include<iostream>
#include<iomanip>
#include<string>
#include<cstdio>
using namespace std;
double result;
int tag;
template<class T>
class arrayStack
{
   public:
       arrayStack();
       ~arrayStack() {delete [] stack;}
       bool empty() const {return stackTop == -1;}
       int size() const
          {return stackTop + 1;}
       T& top(){return stack[stackTop];}
       void pop(){stack[stackTop--].~T();}  // T的析構 
       void push(const T& theElement){stack[++stackTop] = theElement;}
      
   private:
      int stackTop;         // 當前棧頂 
      int arrayLength;      // 棧容量
      T *stack;           // 元素數組 
};
template<class T>//構造函數 
arrayStack<T>::arrayStack()
{
   arrayLength = 2000;
   stack = new T[2000];
   stackTop = -1;
}
arrayStack<double> num;//數字 
arrayStack<char> sign;//運算符

int priority(char a)
{
 if(a=='(')
    return 0;
 else if(a == '+')
    return 1;
 else if(a =='-')
  return 2;
 else if(a == '*')
  return 3;
 else if(a == '/')
  return 3;
 return 0;
}

bool judge(char e)//判斷是運算符還是數字 
{
 bool judge=false; 
 if(e>='0' && e<='9')//不能用'0'<=e<='9' 
 {
  judge=true;
 }
 return judge;
}

void pop_caculate()
{
 double l=0,r=0,w=0;
 char ssign=sign.top();
 r=num.top();
 num.pop();
 l=num.top();
 num.pop();
 sign.pop();
 if(ssign == '+') w=l+r;
 else if(ssign == '-') w=l-r;
 else if(ssign == '*') w=l*r;
 else if(ssign == '/') w=l/r;
 num.push(w);
}
void caculate(string expr)//計算函數 
{
 double n=0;
 string::size_type size=0;
 for(string::size_type i=0;i<expr.size();)
 { 
  if(tag==0 && judge(expr[i])==true)
  {
  n=(double)(expr[i]-48);
  if(sign.top()=='-')
  {
   n=(-1.00)*n;
   sign.pop();
   sign.push('+');
  }
  num.push(n);
  i++;
  tag=1;
  } 
  else{
   tag=0;
   if(sign.empty())
   {sign.push(expr[i]);}
   else if(expr[i]=='(')
   {sign.push(expr[i]);}
   else if(expr[i]==')')
   {
    while(sign.top()!='(')
    {
     pop_caculate();
    }
    sign.pop();
    if(sign.top()=='-')
    {
     num.top()=(-1.00)*num.top();
     sign.pop();
     sign.push('+');
    }   
   }
   else if(priority(expr[i])<=priority(sign.top()))
   {
    pop_caculate();
    sign.push(expr[i]);
   }
   else  sign.push(expr[i]);
   ++i;
  }
 }
 while(!sign.empty())
 {
  pop_caculate();
 }
 result=num.top();
 //cout.setf(ios::fixed,ios::floatfield);
 //cout<<result<<endl;
 printf("%.2f",result);
 cout<<endl;
}
int main()
{
 //freopen("a.txt","r",stdin);
 int n;
 cin>>n;
 for(int i=0;i<n;i++)
 {
  string x;
  cin>>x;
  tag=0;
  caculate(x);
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章