【HDU 1237】简单计算器(后缀表达式+栈的应用)

简单计算器

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15707    Accepted Submission(s): 5362


Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
 
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
 
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
 
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
 
Sample Output
3.00 13.36
 




        对于栈的基本操作。题很好理解,也很好想,但是程序需要考虑的点很多,难点主要在于如何将代数式转化为后缀表达式。

        另推荐HUBRST的OJ的1572题  http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1572    是本题的进阶,理解本题思路就很简单了。

        代码如下:

#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
stack<char> op;
stack<double> num;
char a[205],aa[205];
int oper(char o)             ///用来判断运算符的优先级
{
    if(o=='+') return 1;
    if(o=='-') return 1;
    if(o=='*') return 2;
    if(o=='/') return 2;
    return -1;
}
void hz(char *x)             ///转为后缀表达式
{
    int len=strlen(x);
    int k=0;
    memset(aa,'',sizeof(aa));
    for(int i=0;i<len;i++)
    {
        if(x[i]==' ') continue;   ///如果是空格直接跳过
        aa[k++]=' ';              ///空格用来隔开数字
        while(x[i]>='0'&&x[i]<='9')
            aa[k++]=x[i++];       ///是数字直接存入数组
        if(oper(x[i])!=-1)
        {
            if(oper(x[i])==1)
            {
                while(!op.empty())
                {
                    aa[k++]=op.top();
                    op.pop();
                }
            }
            else
            {
                while(!op.empty()&&oper(op.top())==2)
                {
                    aa[k++]=op.top();
                    op.pop();
                }
            }
            op.push(x[i]);           ///操作符入栈
        }
    }
    while(!op.empty())
    {
        aa[k++]=op.top();
        op.pop();
    }
}
double yunsuan(double x,char c,double y)        ///运算
{
    if(c=='+') return 1.0*x+y;
    if(c=='-') return 1.0*x-y;
    if(c=='*') return 1.0*x*y;
    if(c=='/') return 1.0*x/y;
}
double cal()                            ///计算后缀表达式的值
{
    int len=strlen(aa);
    int k=0;
    double num1=0,num2=0,re;
    while(num.empty()==false)
        num.pop();
    for(int i=0;i<len;i++)
    {
        bool flag=false;
        re=0;
        if(aa[i]==' ') continue;
        while(aa[i]>='0'&&aa[i]<='9')     ///将char型数字转化为int型
        {
            re=re*10+aa[i]-'0';
            i++;
            flag=true;
        }
        if(flag)
            num.push(re);
        if(oper(aa[i])!=-1)               ///碰到操作符就弹出栈顶的2个元素
        {
            num1=num.top();
            num.pop();
            num2=num.top();
            num.pop();
            num.push(yunsuan(num2,aa[i],num1));     ///将运算结果入栈
        }
    }
    return num.top();
}
int main()
{
    while(gets(a))
    {
        if(strcmp(a,"0")==0)  break;
        hz(a);
        printf("%.2lf
",cal());
    }
    return 0;
}






原文地址:https://www.cnblogs.com/Torrance/p/5410571.html