后缀表达式计算

后缀表达式计算

//  test20.cpp : Defines the entry point for the console application.
//

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

class  PostExp{
public :
    PostExp(
string  str):evalStr(str){}
    
int  evaluate();
private :
    
string  evalStr;
    stack
< int >  postStack;
};

/* *
算式中的数字限定在0~9,因为是通过string分别读取每一个元素,如89被认定为8和9
如果操作数要扩大到9以上,则应该用数组保存算式中的每一个元素
此处为方便起见,只是为了表达后缀表达式的基本算法
*/
int  PostExp::evaluate(){ // 后缀表达式计算
     for ( string ::iterator iter = evalStr.begin(); iter != evalStr.end(); iter ++ ){ // 从前至后读取
         int  x,y,z;
        
if ( * iter >= ' 0 '   &&   * iter <= ' 9 ' )
            postStack.push(
* iter  -   ' 0 ' ); // 如果读到数字,压栈
         else { // 如果读到操作符,出栈两个操作数,并计算
            y = postStack.top(); // y保存操作符右边的数字
            postStack.pop();
            x
= postStack.top(); // x保存操作符左边的数字
            postStack.pop();
            
switch ( * iter){
                    
case   ' + ' : z = x + y;  break ; // z保存计算结果
                     case   ' - '  : z = x -  y;  break ;
                    
case   ' * ' : z = x * y;  break ;
                    
case   ' / '  : z = x / y;   break ;
            }
            postStack.push(z);
// 把计算结果作为操作数压栈
        }
    }
    
return  postStack.top();
}

int  main(){
    PostExp
*  pe = new  PostExp( " 352*5+- " );
    cout
<< pe -> evaluate();
    system(
" pause " );
}

你可能感兴趣的:(后缀表达式计算)