计算后缀表达式C/C++

#include <bits/stdc++.h>
using namespace std;

int Cal(int x,int y,char op)
{
    switch(op){
        case '+':    return x+y;
        case '-':    return x-y;
        case '*':    return x*y;
        case '/':    return x/y;
    }

int SuffixExpress(char t[])
{
    stack <char> s;
    int x,y,z;
    for(int i=0;t[i]!='\0';i++){
        if(t[i]==' ')
            continue;
        if(t[i]>='0' && t[i]<='9')
            s.push(t[i]-'0');
        else{
            x=s.top();
            s.pop();
            y=s.top();
            s.pop();
            z=Cal(y,x,t[i]);
            s.push(z);
        }
    }
    return z;
}

int main()
{
    char t[1000];
    gets(t);
    printf("%d\n",SuffixExpress(t));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/linyuan703/article/details/81220971