表达式求值

/*
表达式求值,需要设置两个栈,操作符栈、数字栈。 
add(x,y) sub(x,y) min(x,y) max(x,y)  
*/
#include<stdio.h>
#include<ctype.h>
#define MAX 300
int main()
{
    freopen("express.in", "r", stdin); 
    freopen("estdout.pc2", "w", stdout);   
    int fuhao_stack[MAX], data_stack[MAX], top_f=0, top_d=0;
    int indigit=0, sum=0, i, oper, x, y, r, N;
    char s[MAX];

    scanf("%d", &N);
    while(N--)
    {
    scanf("%s", s);
    i=0;
    while(s[i]!='\0') //分析字符串,剥离运算符、数字(需要将连续的数字字符合成一个整型数据),
    {                  //并分别将运算符和整合出来的整数压栈
        //  printf("=====处理 %c :\n", s[i]);   //本句可测试用

        if( !isdigit(s[i]) )  //不是数字字符
        {   
            if(indigit)  //如果前一个字符是数字,当前字符不是数字,则连续数字字符结束。
            {
                data_stack[top_d++]=sum;
                // printf("sum=%d\n", sum);  //本句可测试用
                indigit=0;  //现在进入非数字字符状态 
            }
            switch(s[i])
            {
            //printf("\n in s ch=%c\n", s[i]);
            case ',':  i++;  break;
            case 'a':  fuhao_stack[top_f]=1;  top_f++;  i=i+4;  break;
            case 's':  fuhao_stack[top_f]=2;  top_f++;   i=i+4; break;
            case 'm':  
                if(s[i+1]=='i')  { fuhao_stack[top_f]=3;  top_f++;  i=i+4;  break; }
                else    {  fuhao_stack[top_f]=4;  top_f++;  i=i+4;  break;  }

            case ')':    //遇到右括号,则可以做运算了(使用最近遇到的运算符) 
                y=data_stack[--top_d];   //到数字栈里取两个数据。 
                x=data_stack[--top_d];
                oper=fuhao_stack[--top_f];   //到符号栈里取运算符 
                switch(oper){  //根据运算符做运算 
                    case 1:  r=x+y;      break;
                    case 2:  r=x-y;    break;   //做减法时,注意是谁减谁 
                    case 3:  r=x<y?x:y;  break;
                    case 4:  r=x>y?x:y;    break;
                }
                data_stack[top_d++]=r;
                i++;   //case ')'
            }
        }  不是数字字符

        else    //是数字字符,转化为整数,累加
        {
            if(!indigit) ///若是第1个数字字符
                {  sum=0;  indigit=1;  }  //累加器清0,准备累加, 设置进入数字状态标志 
            sum=sum*10+s[i]-'0';  //将数字字符转化成整数,并累加。注意原来的数前移1位(扩大10倍 ) 
            i++;
            //printf("\n===sum=%d \n", sum);    //本句可测试用

        }           
    }

    printf("%d\n", data_stack[top_d-1]);
    sum=0;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值