You must have a main function, a parse function, a displayValues function, a pus
ID: 3629062 • Letter: Y
Question
You must have a main function, a parse function, a displayValues function, a push function and a pop function. You must use switch case statements. All variables must be declared inside functions…that means no static variables because one of the objectives of this assignment is passing data to functions and returning results and static (i.e. global) variables defeat this.
you should enter one number or operator at a time ie:
1<enter>
2<enter>
+<enter>
after each entry the stack should be displayed ie:
1<enter>
the stack in decimal is:
1
2<enter>
the stack in decimal is:
1
2
3<enter>
the stack in decimal is:
1
2
3
+<enter>
the stack in decimal is:
1
5
Your calculator must support the following basic operations:
+ add
- subtract
* multiply
/ divide
h hex (stack should be displayed in hex hint:change printf function)
o octal(stack should be displayed in octal hint:change printf function)
d decimal
c change sign
& bitwise and
| bitwise or
^ bitwise xor
~ complement
> right shift
Explanation / Answer
#include #include /* for atof() */ #include #define MAXOP 100 /* max size of operand or operator */ #define NUMBER '0' /* signal that a number was found */ #define MAXVAL 100 /* maximum depth of val stack */ int getop(char []); void push(double); double pop(void); int getch(void); void ungetch(int); int sp = 0; /* next free stack position */ double val[MAXVAL]; /* value stack */ /* push: push f onto value stack */ void push(double f) { if (sp 0) return val[--sp]; else { printf("error: stack empty "); return 0.0; } } main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor "); break; case ' ': printf(" %.8g ", pop()); break; default: printf("error: unknown command %s ", s); break; } } return 0; } /* getop: get next character or numeric operand */ int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == ' ') ; s[1] = ''; if (!isdigit(c) && c != '.') return c; /* not a number */ i = 0; if (isdigit(c)) /* collect integer part */ while (isdigit(s[++i] = c = getch())) ; if (c == '.') /* collect fraction part */ while (isdigit(s[++i] = c = getch())) ; s[i] = ''; if (c != EOF) ungetch(c); return NUMBER; }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.