2012. 7. 13. 14:39

#include <stdio.h>
#include <stdlib.h>

#define MAX 20

void push(int *top,float *stack,float item) {
        if(*top >= MAX-1) {//overflow
                fprintf(stderr,"\nStack Overflow ");
                exit(1);
        }
        else {
                stack[++(*top)] =item;
        }
}

float pop(int *top,float *stack) {
        float item; // 아이템
        if(*top == -1) {//stackunderflow
                fprintf(stderr,"\nStack Underflow");
        }
        else {
                item = stack[(*top)--]; // 할당 후 top 감소
        }
        return item;
}

float oper(int *top,float *stack,char *postfix,int n) {
        float r_value,l_value;
        for (int i=0 ; i<n-1 ; i++) {
                if ((postfix[i]=='*')||(postfix[i]=='/')||(postfix[i]=='+')||(postfix[i]=='-')) {
                        r_value = pop(top,stack); //right_value
                        l_value = pop(top,stack); //left_value
                        if (postfix[i] == '+') push(top,stack,l_value+r_value);
                        else if (postfix[i] == '-') push(top,stack,l_value-r_value);
                        else if (postfix[i] == '*') push(top,stack,l_value*r_value);
                        else push(top,stack,l_value/r_value);
                }
                else {
                        push(top,stack,(float)(postfix[i]-'0'));
                }
        }
        return pop(top,stack);
}

int show_menu() {
        int order;
        printf("=============================================");
        printf("\nPostfix로 변환된 식은(234*+56/2*3/-4+)입니다.");
        printf("\n1)결과 보기 2)EXIT");
        printf("\n=============================================\n");
        scanf("%d",&order);
        return order;
                
}

int main() {
        char postfix[]="234*+56/2*3/-4+"; //infix -- > postfix로 변환된 식
        //char oper[5]={'+','-','*','/'};
        float stack[MAX];
        int top=-1;
        while(1) {
                switch(show_menu()) {
                case 1 :
                        printf("\n최종값은 %f\n",oper(&top,stack,postfix,sizeof(postfix)/sizeof(char)));
                        break;
                case 2 :
                        printf("\n종료\n");
                        exit(1);
                        }
        }
        return 0;
}

Posted by 몰라욧