-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostsol.c
63 lines (62 loc) · 1.22 KB
/
postsol.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 80
float eval(char expr[]);
float oper(char symb,float op1, float op2);
void push(float items[], int *top, float e);
float pop(float items[],int *top);
void main()
{
char expr[MAX];
printf("Enter the postfix expression \n");
fgets(expr,80,stdin);
printf("The orginal postfix expression = %s \n",expr);
printf("%6.2f \n",eval(expr));
}
float eval(char expr[])
{
char c;
int pos;
float res,op1,op2,r,s[MAX];
int top = -1;
for(pos = 0;(c = expr[pos])!='\0';pos++)
{
if(isdigit(c))
push(s,&top,(float)(c - '0'));
else
{
op2 = pop(s,&top);
op1 = pop(s,&top);
r = oper(c,op1,op2);
push(s,&top,r);
}
}
res = pop(s,&top);
return res;
}
float oper(char symb,float op1, float op2)
{
switch(symb)
{
case '+':return (op1+op2);
case '-':return (op1-op2);
case '*':return (op1*op2);
case '/':return (op1/op2);
case '^':
case '$':return (float)pow(op1,op2);
case '%':return (float)((int)op1 % (int)op2);
default: printf("%s illegal operator \n",symb);
exit(1);
}
}
void push(float items[], int *top, float e)
{
items[++(*top)] = e;
}
float pop(float items[],int *top)
{
return items[(*top)--];
}