后缀表达式计算

来源:互联网 发布:php图片生成器 编辑:程序博客网 时间:2024/05/27 20:52
#include <iostream>#include <stack>#include<stdio.h>#include<stdlib.h>#include<string.h>using namespace std;//  9 3 1 - 3 * + 10 2 / +int main( ){    int k;    char a[210];    stack<long>s;    scanf("%d",&k);    getchar();    while(k--)    {        memset(a,0,sizeof(a));        gets(a);        int res=0;        for(int i=0;i<strlen(a);i++)        {            int temp=0;            int flg=0;            //if(a[i]>='0'&&a[i]<='9')            //{                while(a[i]>='0'&&a[i]<='9')                {                    temp=temp*10+a[i]-'0';                    i++;                    flg=1;                }                if(flg==1){s.push(temp);flg=0;}            //}            if(a[i]==' ')            {                continue;            }            if(a[i]!=' '&&!(a[i]>='0'&&a[i]<='9'))            {                int op1=s.top();s.pop();                int op2=s.top();s.pop();                if(a[i]=='+') res=op2+op1;                else if(a[i]=='-') res=op2-op1;                else if(a[i]=='*') res=op2*op1;                else if(a[i]=='/') res=op2/op1;                else if(a[i]=='%')res=op2%op1;                s.push(res);            }        }        printf("%d\n",s.top());    }    return 0;}
1 0
原创粉丝点击