表示式計算 用棧完成

zzj_4ever發表於2007-01-14

 

///////////////////////////////
///表示式計算
////資料結構:棧
////作者:ZZJ_4Ever
///////////////////////////////


#include 
<iostream>
#include 
<stack>
#include 
<string>
#include
<assert.h>
using namespace std;

stack
<double> data_stack;
stack
<char> char_stack;
int PRI(char &ch)
{
 
if(ch==')'){return 1;}
 
else if(ch=='+'||ch=='-'){return 2;}
 
else if(ch=='*'||ch=='/'){return 3;}
 
else return 0;
}

/*
2.掃描到操作符,與操作符棧的頂端操作符進行比較,
   如果優先順序小或相等,則彈出資料和操作符進行計算,將結果送入資料棧;
   如果優先順序較大,則進操作符棧;
   如果是’(‘直接進棧,如果是’)’,遇到’(‘則抵消.
*/

void Exc_stack()

 
 
double result_temp;
 assert(char_stack.size()
>=1&&data_stack.size()>=1);
 
double temp1=data_stack.top();
 data_stack.pop();
 
double temp2=data_stack.top();
 data_stack.pop();
 
char popchar=char_stack.top();
 char_stack.pop();
 
if(popchar=='+')
 result_temp
=temp2+temp1;
 
else if(popchar=='-')
 result_temp
=temp2-temp1;
 
else if(popchar=='*')
 result_temp
=temp2*temp1;
 
else if(popchar=='/')
 result_temp
=temp2/temp1;
 data_stack.push(result_temp);
}

void push_charinto(char &ch)

 
if(ch=='(')//如果是’(‘直接進棧
  char_stack.push(ch);
 
else if(char_stack.empty())
 
{
  char_stack.push(ch);
  
 }

 
else if(PRI(ch)>PRI(char_stack.top()))//如果優先順序較大,則進操作符棧
 {
  char_stack.push(ch); 
 }

 
//掃描到操作符
 else//如果優先順序小或相等,則彈出資料和操作符進行計算,將結果送入資料棧
 {
  
  Exc_stack();
  
  
if(ch==')')//如果是’)’,遇’(‘直接彈出.
  {
   
while(char_stack.top()!='(')//操作括號內的內容直到遇到'('為止
   {
    Exc_stack();
   }

   char_stack.pop();
  }

  
else
  
//將自己壓入棧
  char_stack.push(ch);
 }
 
}

void push_datainto(double &db)
{

 data_stack.push(db);
}

void main()
{
 
string str;
 
 
while(1)
 

  
bool flag=false;
  
double ret = 0.0;
  
double n ;
  cout
<<"在此輸入表示式:";
  
//讀 入 
  cin>>str;
  
//處理

  
//篩選
  ////////////////////////
  
/////開始掃描
  
/////////////////////// 

  for(int i=0;i<str.length();i++
  
{
   
   
if(str[i]>='0' && str[i]<='9')
   
{
    
if(!flag)
     ret 
= ret *10 + str[i]-'0';
    
else
    
{
     ret 
= ret + (str[i]-'0')/n;
     n
*=10;
    }

   }

   
else if(str[i] == '.')
   
{
    n 
= 10;
    flag 
= true;
   }

   
else
   
{
    
if(ret!=0 || str[i-1]=='0')
    push_datainto(ret); 
    ret
=0.0;
    flag 
= false;
    push_charinto(str[i]);
   }

  
  }

  
//如果最後一個數字還沒有壓入棧
  if(ret!=0||str[i-1]=='0')push_datainto(ret);
  
//3.掃描資料完成後,依次退棧並進行計算
  assert(!data_stack.empty()||!char_stack.empty());
  
while(data_stack.size()!=1)
  
{
   Exc_stack();
  }

 
// double rre=data_stack.top();
  cout<<"結果:"<<data_stack.top()<<endl;
  data_stack.pop();
 }

}

相關文章