hdu

    技术2025-06-22  18

    /* 开两个栈,一个保存运算符,一个保存数字,每遇到一个运算符,就与栈顶的运算符进行 比较优先级... */ #include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<stack> using namespace std; char s[300]; int priority(char a,char b)   // 优先级 {     int x,y;     if(a=='+'||a=='-')         x=1;     else         x=2;     if(b=='+'||b=='-')         y=1;     else         y=2;     return x-y; } double cal(double a,double b,char x)    // 计算 {     switch(x)     {     case '+':return a+b;break;     case '-':return a-b;break;     case '*':return a*b;break;     case '/':return a/b;break;     } } int main() {     while(gets(s))     {         double a,b;         int len=strlen(s);         if(len==1&&s[0]=='0')             break;         stack<double>num;         stack<char>oper;         int i,j;         for(i=0;i<len;i++)         {             if(s[i]>='0'&&s[i]<='9')             {                 a=(double)(s[i]-'0');             while(i+1<len&&s[i+1]!=' ')             {                 i++;                 a=a*10+s[i]-'0';             }                 num.push(a);             }             else if(s[i]!=' ')             {                 if(!oper.empty())                 {                     if(priority(oper.top(),s[i])>=0)                     {                         a=num.top();                         num.pop();                         b=num.top();                         num.pop();                         num.push(cal(b,a,oper.top()));                         oper.pop();                         oper.push(s[i]);                     }                     else                     {                         a=num.top();                         num.pop();                         b=(double)(s[i+2]-'0');                         char x=s[i];                         i+=2;                         while(i+1<len&&s[i+1]!=' ')                         {                          i++;                          b=b*10+s[i]-'0';                         }                         num.push(cal(a,b,x));                     }                 }                 else                     oper.push(s[i]);             }         }         if(!oper.empty())         {             a=num.top();             num.pop();             b=num.top();             printf("%.2lf/n",cal(b,a,oper.top()));         }         else         printf("%.2lf/n",num.top());     }     return 0; }

    最新回复(0)