简单计算器--hdu1237(栈的运用)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237

 这是单纯的本题答案;

#include<stdio.h>
#define N 1100
int main()
{
    int a,j,i;
    double Sum[N],sum;
    char c1,c2,c;
    while(scanf("%d",&a)!=EOF)
    {
        sum=0;
        Sum[0]=a;
        c=getchar();
        j=1;
        if(a==0&&c!=' ')
            break;
        while(scanf("%c %d%c",&c1,&a,&c2)!=EOF)
        {
            if(c1=='+')
                Sum[j++]=1.0*a;
            else if(c1=='-')
                Sum[j++]=-1.0*a;
            else if(c1=='*')//注意区分Sum[j--]*=a与Sum[j-1]*=m;
                Sum[j-1]*=a;
            else if(c1=='/')
                Sum[j-1]/=(1.0*a);
            if(c2!=' ')
                break;
        }
        for(i=0;i<j;i++)
            sum+=Sum[i];
        printf("%.2lf\n",sum);

    }
}
View Code

后来用栈写了一下,大话数据结构中关于前缀表达式和后缀表达式讲的很清楚, 下面是一个可以包含括号的

 

一种不需要括号的后缀表达法,成为逆波兰表达式,也叫后缀表达式

标准的四则运算表达式,即"9+(3-1)*3+10/2"叫做中缀表达式

将中缀表达式转换为后缀表达式的规则:

从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分;若是符号,则判断其与栈顶符号的优先级,是右括号或优先级不高于栈顶符号(乘除优先加减)则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<queue>
#define N 110
#define met(a, b) memset(a, b, sizeof(a))
using namespace std;

stack<char> F;
stack<double> num;

int J(char ch)
{
    if(ch == '+' || ch == '-')return 1;
    if(ch == '*' || ch == '/')return 2;
    if(ch == '(' || ch == ')')return 3;
    return 0;
}
double slo(double a, double b, char ch)
{
    if(ch == '+')return a+b;
    if(ch == '-')return a-b;
    if(ch == '*')return a*b;
    return a/b;
}
void slove()
{
    double a = num.top(); num.pop();
    double b = num.top(); num.pop();
    char ch = F.top(); F.pop();
    double m = slo(b, a, ch);
    num.push(m);
}
int main()
{
    char s[N];

    while(gets(s), strcmp(s, "0"))
    {
        while(F.size())F.pop();

        while(num.size())num.pop();

        int len = strlen(s);

        for(int i=0; i<len; i++)
        {
            if(s[i]>='0' && s[i]<='9')
            {
                double m = 0;
                while(i<len && s[i]>='0' && s[i]<='9')
                {
                    m = m*10 + s[i]-'0';
                    i++;
                }
                if(i!=len)i--;
                num.push(m);
            }
            else if(J(s[i]))
            {
                while(F.size() && J(s[i])!=3 && J(F.top())!=3 && J(s[i]) <= J(F.top()) ) slove();
                if(s[i] != ')')F.push(s[i]);
                else
                {
                    while( F.top()!='(' )slove();
                    F.pop();
                }
            }
        }
        while(F.size())slove();
        printf("%.2f\n", num.top());
    }
    return 0;
}
View Code

 

posted @ 2015-03-16 20:01  西瓜不懂柠檬的酸  Views(191)  Comments(0Edit  收藏  举报
levels of contents