逆波兰表达式求值

61 阅读1分钟

样例输入

2 3 5 + *

样例输出

16

程序代码:

#include<stdio.h>
#include<stack>
using namespace std;
char str[110];
int main()
{
    stack<int>s;
    int a,b,i,j,sum=0;
    while(scanf("%[^\n]",str)!=EOF)
    {
        getchar();
        for(i=0;str[i]!='\0';i++)
        {
            if(str[i]==' ')
                continue;
            sum=0;
            while(str[i]>='0'&&str[i]<='9')
            {
                sum=10*sum+str[i]-'0';
                i++;
            }
            if(str[i]=='+')
            {

                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                s.push(a+b);
            }
            else if(str[i]=='-')
            {
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                s.push(a-b);
            }
            else if(str[i]=='*')
            {
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                s.push(a*b);
            }
            else if(str[i]=='/')
            {
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                s.push(a/b);
            }
            else
               s.push(sum);
        }
        printf("%d\n",s.top());
    }


    return 0;

}