简单表达式求值(用栈实现)

#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
char Compare(char x,char y)
{
    char c[][8]={">><<<>>",
                 ">><<<>>",
                 ">>>><>>",
                 ">>>><>>",
                 "<<<<<=e",
                 ">>>>e>>",
                 "<<<<<e="
                };
    int a[100];
    a['+']=0;a['-']=1;a['*']=2;a['/']=3;a['(']=4;a[')']=5;a['#']=6;
    return c[a[x]][a[y]];
}
float Execute(float a,char o,float b)
{
    switch(o)
    {
    case'+':return a+b;
    case'-':return a-b;
    case'*':return a*b;
    case'/':return a/b;
    }
    return 0;
}
float ExpEvaluation()
{
    char ch,ch1;
    float a,b,v;
    stack<float> D;
    stack<char> R;
    printf("Please input an expression(Ending with #):\n");
    R.push('#');
    cin>>ch;
    //ch=getchar();
    while(ch!='#'||R.top()!='#')
    {
        if(ch>='0'&&ch<='9')
        {
            int temp=ch-'0';
            cin>>ch;
            //ch=getchar();
            while(ch>='0'&&ch<='9')
            {
                temp=temp*10+ch-'0';
                cin>>ch;
                //ch=getchar();
            }
            D.push(temp);    
        }
        else
        {
            switch(Compare(R.top(),ch))
            {
            case'<':R.push(ch);
                    cin>>ch;
                     //ch=getchar();
                    break;
            case'=':R.pop();
                    cin>>ch;    
                    //ch=getchar();
                    break;
            case'>':ch1=R.top();
                    R.pop();
                    b=D.top();
                    D.pop();
                    a=D.top();
                    D.pop();
                    v=Execute(a,ch1,b);
                    D.push(v);
                    break;
            }
        }
    }
    v=D.top();
    return v;
}
int main()
{
    float ans;
    while(1)
    {
        ans=ExpEvaluation();
        /*getchar();前面用getchar()插入的的时候最后我们用回车输出结果,
        这里的getchar()用于吸收回车,而且用getchar()输入的话多数输空格
        或者回车就会报错,这里要吸收回车就是一个例子*/
        printf("%.4f\n",ans);
    }
    return 0;
}

 

posted @ 2012-08-03 17:02  myth_HG  阅读(475)  评论(0编辑  收藏  举报