用栈求中缀表达式值



int getPriority(char op)      #判断运算符优先级
{
    if(op == '+' || op == '-')
        return 0;
    else
        return 1; 
}

int calSub(float opand1, char op, float opand2, float &result)       #子表达式求值
{
    if(op == '+')  result = opand1+opand2;
    if(op == '-')  result = opand1- opand2;
    if(op == '*')  result = opand1 * opand2;
    if(op == '/') 
    {
        if(fabs(opand2) < MIN)     #fabs() 求绝对值,MIN几乎为零,对float是否为零的标准写法,不直接判断为零,而是用这种接近的方式
        {
            return 0;
        }
        else
        {
            result = opand1 / opand2;
        }
    }
    return 1;
}
//求解中缀表达式
float calInfix(char exp[ ])
{
    //定义两个栈并且初始化
    float s1[maxSize]; int top1 = -1;      //存操作数
    char s2[maxSize]; int top2 = -1;      //存运算符
    int i = 0;
    while(exp[i] != '')      //‘'为结束符
    {
        if('0' <= exp[i] && exp[i] <= '9')
        {
            s1[++top1] = exp[i] - '0';       //将字符型转换为数值型
            ++i;
        }
        else if(exp[i] == '(')
        {
            s2[++top2] = '(';
            ++i;
        }
        else if (exp[i] == '+' || exp[i] == '-' ||
                    exp[i] == '*' ||exp[i] == '/'  )
        {
            if(top2 == -1 || s2[top2] == '(' || getPriority(exp[i]) > getPriority(s2[top2]))//当栈空或为左括号或当前优先级>栈顶优先级时入栈
            {
                s2[++top2] = exp[i];
                ++i;
            }
            else
            {
               int flag = calStackTopTwo(s1, top1, s2, top2);
               if(flag == 0)
                return 0;
            }
        }
        else if(exp[i] == ')')
        {
            while(s2[top2] != '(')
            {
                 int flag = calStackTopTwo(s1, top1, s2, top2);
                 if(flag == 0)
                return 0;
            }
            --top2;
            ++i;
        }
    }
    while(top2 != -1)
    {
         int flag = calStackTopTwo(s1, top1, s2, top2);
         if(flag == 0)
                return 0;
    }
    return s1[top1];
}
//将重复的部分写成函数
int calStackTopTwo(float s1[ ], int &top1, char s2[ ], int &top2)
{
     float opand1, opand2, result;      //opand1, opand2接收出栈操作数,result是运算符结果
                char op;      //运算符
                int flag;
                opand2  = s1[top1--];
                opand1 = s1[top1--];
                op = s2[top2--];
                flag = calSub(opand1, op, opand2, result);
                if(flag == 0) {
                    std::count<<"ERROR" << std::end1;     //puts("ERROR");
                }  
                s1[++top1] = result;
                return flag;
}

//


原文地址:https://www.cnblogs.com/dsbz/p/14426079.html