zoukankan      html  css  js  c++  java
  • 逆波兰表达式

     以输入正确的逆波兰表达式为前提,计算结果。。。

    #define MAXSIZE 10
    typedef struct Node
    {
        double data;
        struct Node *next;
    }Node;
    
    typedef struct Stack
    {
        Node *top;
    }Stack;
    
    void s_push(Stack *s, double data);
    void s_pop(Stack *s, double *d);
    
    
    int main()
    {
        Stack s = {NULL};
        char l[MAXSIZE] = {0};
        char el;
        double d,e;
        int i = 0;
        
        printf("输入逆波兰表达式,以#结尾:
    ");
        scanf("%c", &el);
        
        while(el!='#')
        {
            if(isdigit(el) || el == '.')
            {
                l[i] = el;
                l[i+1] = '';
            }
            if(el == ' ')
            {
                if(l[0]) {
                    s_push(&s, atof(l));
                    l[0] = '';
                    i = 0;
                }
                
            }
            
            switch(el)
            {
                case '+':
                    s_pop(&s, &e);
                    s_pop(&s, &d);
                    s_push(&s, d+e);
                    break;
                case '-':
                    s_pop(&s, &e);
                    s_pop(&s, &d);
                    s_push(&s, d-e);
                    break;
                case '*':
                    s_pop(&s, &e);
                    s_pop(&s, &d);
                    s_push(&s, d*e);
                    break;
                case '/':
                    s_pop(&s, &e);
                    s_pop(&s, &d);
                    if(e == 0) {
                        printf("除数为0");
                        exit(-1); 
                    }
                    s_push(&s, d/e);
                    break;
            }
            
            scanf("%c", &el);
        }
        
        s_pop(&s, &d);
        printf("计算结果:%f", d);
        
        return 0;
    }
    
    void s_push(Stack *s, double data)
    {
        Node *p = (Node *)malloc(sizeof(Node));
        p->data = data;
        p->next = s->top;
        s->top = p;
    }
    
    void s_pop(Stack *s, double *d)
    {
        Node *p = s->top;
        if(p == NULL)
        {
            return ;
        }
        *d = p->data;
        s->top = p->next;
        free(p);
        
    }
  • 相关阅读:
    js中的投掷筛子的小游戏
    js俩习题
    python中socket理论
    python实现计时器(装饰器)
    python之正则表达式(re模块)用法总结
    python练习题之随机生成验证码
    python中模块介绍
    python中的装饰器基本理论
    python类与对象练习题扑克牌
    Java抓取网页数据
  • 原文地址:https://www.cnblogs.com/buerr/p/7359090.html
Copyright © 2011-2022 走看看