#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX 50
#define TRUE 1
#define FALSE 0
struct stack{
int top;
double items[MAX];
};
int digit(char symb)
{
return (symb>='0' && symb<='9');
}
void push(struct stack *ps,double n)
{
ps->items[++(ps->top)]=n;
}
double pop(struct stack *ps)
{
return ps->items[(ps->top)--];
}
double oper(int symb, double op1, double op2)
{
switch (symb)
{
case '+':return (op1+op2);
case '-':return (op1-op2);
case '*':return (op1*op2);
case '/':return (op1/op2);
case '%': return (fmod(op1,op2));
default: printf("Invalid operation..."); exit(1);
}
}
double eval(char expr[])
{
struct stack ps;
ps.top=-1;
int c,position;
double oprd1,oprd2,result;
for(position=0; ( c = expr[position] ) != '\0'; position++)
if(digit(c))
push(&ps,(double)(c-'0'));
else
{
oprd2 = pop(&ps);
oprd1 = pop(&ps);
result = oper(c,oprd1,oprd2);
push(&ps,result);
}
return (pop(&ps));
}
int main()
{
char expr[MAX];
int position = 0;
while( (expr[position++]= getchar() )!='\n') // to read expression.
;
expr[--position]='\0';
printf("Origional Expression: %s\n",expr);
printf("%f\n", eval(expr));
return 0;
}
No comments:
Post a Comment