欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

表达式求值

程序员文章站 2022-03-31 19:52:28
...

#include
#include
#include
#include
#include
#include

using namespace std;
const int MAXN = 1010;

int priority(char c) // 表达优先级的大小关系
{
if (c == ‘*’ || c == ‘/’) return 2;
if (c == ‘+’ || c == ‘-’) return 1;
return 0;
}

void cal(stack &my_op, stack &my_num) // 将数字栈与操作栈通过引用的形式实现调用与更改
{
double b = my_num.top();
my_num.pop();
double a = my_num.top();
my_num.pop();
switch(my_op.top())
{
case ‘+’:
my_num.push(a + b);
break;
case ‘-’:
my_num.push(a - b);
break;
case ‘*’:
my_num.push(a * b);
break;
case ‘/’:
my_num.push(a / b);
break;
}
my_op.pop();
}

int main()
{

 int t;
 scanf("%d", &t);
 while(t --)
 {
     char s[MAXN];
     scanf("%s", s);
     int len = strlen(s);
     stack <double> my_num;
     stack <char> my_op;

     for(int i = 0; i < len; ++ i)
     {
         if(isdigit(s[i]))      //如果s[i]是数字,不是符号 
         {
             double temp = atof(&s[i]);     //字符串转化为浮点数 
             while(isdigit(s[i]) || s[i] == '.') ++ i;
             my_num.push(temp);
             -- i;
         }
         else if(s[i] == '(')
         {
             my_op.push(s[i]);
         }
         else if(s[i] == ')')
         {
            while(my_op.top() != '(')
                 cal(my_op, my_num);
             my_op.pop();
         }
         else if(my_op.empty())
         {
             my_op.push(s[i]);
         }
         else if(priority(my_op.top()) < priority(s[i]))
         {
             my_op.push(s[i]);
			              }
         else if(priority(my_op.top()) >= priority(s[i]))
        {
             while(!my_op.empty() && priority(my_op.top()) >= priority(s[i])) // 比较的是优先级关系不是ASCⅡ,
                 cal(my_op, my_num);
             my_op.push(s[i]);
			              }
    }
     my_op.pop();
     printf("%.2lf\n", my_num.top());
    my_num.pop();
 }
 return 0;

}