随笔 - 6  文章 - 3  trackbacks - 0
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

/***************************

表达式模板

***************************
*/

#include
<stack>
#include
<string>
#include
<iostream>
using namespace std;

int signMap[7][7]=

    
{'>','>','<','<','<','>','>'},    // +
    {'>','>','<','<','<','>','>'},    // - 
    {'>','>','>','>','<','>','>'},    // *
    {'>','>','>','>','<','>','>'},    // /
    {'<','<','<','<','<','=','#'},    // (
    {'>','>','>','>','#','>','>'},    // ) 
    {'<','<','<','<','<','#','='},    // #               
}
;

char element[7]={'+','-','*','/','(',')','#'};

char Precede(char oper1,char oper2)
{
    
int i,j;
    
for(i=0;i<7;i++)
    
{
           
if(element[i]==oper1) break;
    }

    
for(j=0;j<7;j++)
    
{
           
if(element[j]==oper2) break;
    }

    
return signMap[i][j];
}


int Operate(int a,char oper,int b)
{
    
switch(oper)
    
{
        
case '+':
               
return a+b;
               
break;
        
case '-':
               
return a-b;
               
break;
        
case '*':
               
return a*b;
               
break;
        
case '/':
               
return a/b;
               
break;
        
default:
               cerr
<<"Operate Error"<<endl;
               
return 0;
    }

}


int Calculate(string &str)
{
    
int a,b,t2;
    
char oper;
    stack
<int> opnd;
    stack
<char> optr;
    optr.push(
'#'); 
    str
=str+'#';
    
int index=0;
    
while(optr.top()!='#'||str[index]!='#')
    
{
           
while(str[index]==' ') index++;
           
if(!(str[index]=='+'||str[index]=='-'||
        str[index]
=='*'||str[index]=='('||str[index]==')'||str[index]=='#'))
        
{
            opnd.push(str[index
++]-'0');
           }

           
else
        
{
            
char t=Precede(optr.top(),str[index]);
            
switch(t)
            
{
                
case '<':
                     optr.push(str[index
++]);
                     
break;
                
case '=':
                     optr.pop();
                     index
++;
                     
break;
                
case '>':
                     oper
=optr.top();
                     optr.pop();
                     a
=opnd.top();
                     opnd.pop();
                     b
=opnd.top();
                     opnd.pop();
                     t2
=Operate(b,oper,a);
                     opnd.push(t2);
                     
break;
                
default:
                    cerr
<<"Operate Error"<<endl;
                    
return 0;
            }
 
           }

    }
 
    
return opnd.top();
}
posted on 2009-04-17 21:00 姚冰 阅读(244) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理