C语言中缀表达式转后缀表达式并利用后缀表达式求值 (小于10)

来源:互联网 发布:淘宝投诉失败怎么办 编辑:程序博客网 时间:2024/05/13 01:36

#include<stdio.h>

#include<stdlib.h>

int precedence(char c)

{

    if(c=='*'||c=='/')

        return2;

    if(c=='+'||c=='-')

        return1;

    return0;

}

int main()

{

    char stack1[1000];int top_index1=-1;

    char stack2[1000];int top_index2=-1;

    char c;

    while(1)

    {

        scanf("%c",&c);

        if(c=='\n')

            break;

        elseif(c>='0'&&c<='9')

        {

            top_index2++;

            stack2[top_index2]=c;

        }

        elseif(c=='(')

        {

            top_index1++;

            stack1[top_index1]=c;

        }

        elseif(c==')')

        {

            while(stack1[top_index1]!='(')

            {

                top_index2++;

                stack2[top_index2]=stack1[top_index1];

                top_index1--;

            }

            top_index1--;

        }

        elseif(c=='+'||c=='-'||c=='*'||c=='/')

        {

            if(top_index1==-1||precedence(c)>precedence(stack1[top_index1]))

            {

                top_index1++;

                stack1[top_index1]=c;

            }

            else

            {

                while(top_index1>=0&&precedence(stack1[top_index1])>=precedence(c))

                {

                    top_index2++;

                    stack2[top_index2]=stack1[top_index1];

                    top_index1--;

                }

                top_index1++;

                stack1[top_index1]=c;

            }

        }

    }

    while(top_index1!=-1)

    {

        top_index2++;

        stack2[top_index2]=stack1[top_index1];

        top_index1--;

    }

    

   // printf("%s\n",stack2); printf("%d\n",top_index2);

    int stack3[1000];int top_index3=-1;

    for(int i=0;i<=top_index2;i++)

    {

        if(stack2[i]>='0'&&stack2[i]<='9')

        {

            top_index3++;

            stack3[top_index3]=stack2[i]-48;

            continue;

        }

        else

        {

            if(stack2[i]=='+')

            {

                int t1=stack3[top_index3];

                int t2=stack3[top_index3-1];

                top_index3--;

                stack3[top_index3]=t1+t2;

            }

            if(stack2[i]=='-')

            {

                int t1=stack3[top_index3];

                int t2=stack3[top_index3-1];

                top_index3--;

                stack3[top_index3]=t2-t1;

            }

            if(stack2[i]=='*')

            {

                int t1=stack3[top_index3];

                int t2=stack3[top_index3-1];

                top_index3--;

                stack3[top_index3]=t1*t2;

            }

            if(stack2[i]=='/')

            {

                int t1=stack3[top_index3];

                int t2=stack3[top_index3-1];

                top_index3--;

                stack3[top_index3]=t2/t1;

            }

        }

    }

    printf("%d",stack3[0]);

}



阅读全文
0 0