I wrote this code to evaluate a postfx expression but it works for only single digit. I need to make it work for double digit and floats. i.e making it work for something like 1315.5*8+ which is for the infix 13*15.7+8. I don't have problem converting from infix to postfix.
Code:#include<stdio.h> #include<stdio.lib> #define MAXCOLS 80 main(){ char instring[MAXCOLS], postring[MAXCOLS]; int position = 0; float eval(); float result; printf("%s", "Enter postfix expression: "); while ((postring[position++] = getchar()) != '\n'); postring[--position] = '\0'; printf("%s%s", "postfix expression is", postring); getchar(); result=eval(postring); printf("%s%f\n", "value is", result); getchar(); } struct stack{ int top; float items[MAXCOLS]; }; float eval(expr) char expr[]; { int c, position; float op1, op2, value; float oper(), pop(); struct stack opndstk; opndstk.top = -1; for (position =0; (c=expr[position]) != '\0'; position++) if(isdigit(c)) push (&opndstk, (float)(c-'0')); else { op2 = pop(&opndstk); op1 = pop(&opndstk); value = oper(c, op1, op2); push (&opndstk, value); } return (pop(&opndstk)); } float oper(symb, operand1, operand2) int symb; float operand1, operand2; { switch(symb){ case '+': return (operand1 + operand2); case '-': return (operand1 - operand2); case '*': return (operand1 * operand2); case '/': return (operand1 / operand2); default: printf("%s", "illegal operation"); exit(1); } } push(ps, x) struct stack *ps; float x; { if(ps->top == MAXCOLS-1){ printf("%s", "stack overflow"); exit(1); } else ps->items[++(ps->top)] =x; return; } float pop(ps) struct stack *ps; {int top; if (top==-1){ printf("%s", "stack underflow"); exit(1); } else return(ps->items[ps->top--]); }



LinkBack URL
About LinkBacks



