求后缀式数值

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define maxsize 100
using namespace std;

int OP(int a,char op,int b)
{
    if(op=='+') return a+b;
    if(op=='-') return a-b;
    if(op=='*') return a*b;
    if(op=='/')
    {
        if(b==0) {printf("error\n");return 0;}
        else return a/b;
    }
}
int cal(char A[])
{
    int a,b,c,i;
    int stack[maxsize],top=-1;
    char op;
    for(i=0;A[i]!='\0';++i)
    {
        if(A[i]>='0'&&A[i]<='9')
        {
            stack[++top]=A[i]-'0';
        }
        else
        {
            op=A[i];
            b=stack[top--];
            a=stack[top--];
            c=OP(a,op,b);
            stack[++top]=c;
        }
    }
    return c;
}

int main()
{
    char A[maxsize];
    scanf("%s",A);

    printf("%d\n",cal(A));

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39350434/article/details/81274499
今日推荐