栈的应用三——后缀表达式求值

栈的应用三——后缀表达式求值

lixiangrong
2024-01-05 / 0 评论 / 37 阅读 / 正在检测是否收录...
// 将字符转换成数字
double readNumber(char c[],int *i)
{
    double x = 0.0;
    int k = 0;
    while (c[*i] >= '0' && c[*i] <= '9')
        x = x*10 + (c[(*i)++] - '0');
    if(c[*i] == '.')
    {
        (*i)++;
        while (c[*i] >= '0' && c[*i] <= '9')
        {
            x = x*10 + (c[(*i)++] - '0');
            k++;
        }
    }
    while (k != 0)
    {
        x = x/10.0;
        k--;
    }
    return x;
}

// 后缀表达式求值
double cal(char c[])
{
    double op[MAX_SIZE] = {}; // 操作数栈
    int top = 0; // 栈顶指针
    double left,right; // 左、右操作数
    int i = 0;
    while (c[i])
    {
        if(c[i] >= '0' && c[i] <= '9')
            op[top++] = readNumber(c,&i);
        else if(c[i] == ' ') i++;
        else
        {
            right = op[--top];
            left = op[--top];
            if(c[i] == '+')
                op[top++] = left + right;
            else if(c[i] == '-')
                op[top++] = left - right;
            else if(c[i] == '*')
                op[top++] = left * right;
            else
                op[top++] = left / right;
            i++;
        }
    }
    return op[--top];
}

int main()
{
    char c[] = "6/3+(5*6-2*7)/4";
    char r[MAX_SIZE]={};
    convert(c,r);
    int i=0;
    while (r[i])
        printf("%c",r[i++]);
    printf("\n");
    printf("%f",cal(r));
    return 0;
}
0

评论 (0)

取消