后缀算术表达式求值

作者在 2008-04-08 22:55:03 发布以下内容

数字为个位数,不考虑语法错误

#include<stdio.h>

#include<stdlib.h>

#define add  43

#define subs 45

#define mult 42

#define div 47

#define MAXSIZE 100

typedef struct stack

{

    int stkdata[MAXSIZE];

    int top;

};

int init_stack(struct stack *s)

{

    s->top=-1;

    return 1;

}

int push(struct stack *s,char e)

{

    if(s->top==100)

    {

        printf("over flow\n");

        return 0;

    }

    s->stkdata[++(s->top)]=e;

    return 1;

}

char pop(struct stack *s)

{

    char e;

    if(s->top==-1)

    {

        printf("under flow \n");

        return 0;

    }

    e=s->stkdata[(s->top)--];

    return e;

}

void main()

{

    struct stack *s1;

    init_stack(s1);

    int length,i,num1,num2,result,sum;

    char s[100];

    printf("please input \n");

    printf("warning:must less than 100\n");

    gets(s);

    length=strlen(s);

    for(i=0;i<=length-1;i++)

        {

            if(s[i]>='1'&&s[i]<='9')

                push(s1,s[i]-48);

            else

            {

                num1=pop(s1);

                num2=pop(s1);

                switch(s[i])

                {

                    case add:

                    {

                        sum=num1+num2;

                        push(s1,sum);

                        break;

                    }

                    case subs:

                    {

                        sum=num2-num1;

                        push(s1,sum);

                        break;

                    }

                    case div:

                    {

                        sum=num2/num1;

                        push(s1,sum);

                        break;

                    }

                    case mult:

                    {

                        sum=num1*num2;

                        push(s1,sum);

                        break;

                    }

                }

            }

        }

        result=s1->stkdata[s1->top];

        printf("result is %d\n",result);

    }

 

 

默认分类 | 阅读 3405 次
文章评论,共1条
彦宏(作者)
2008-04-09 12:16
1
如果要考虑语法错误,就包括符号与数字不对应的问题,而若是非个位数,那么就要在扫描时判断是符号还是数字,以及是几位数,这样就很复杂,不是简单几行代码可以解决的。
我最近很忙,没办法考虑到这些,当然,你也可以自己解决一下上诉问题,呵呵...
游客请输入验证码
浏览15301次
文章分类