Guest User

Untitled

a guest
Oct 15th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. // from K&R section 4.3
  2. #include <stdio.h>
  3. #include <stdlib.h> // for atof()
  4. #include <ctype.h>
  5.  
  6. #define MAXOP 100 // max size of operand
  7. #define NUMBER '0' // signal that a number was found
  8. #define MAXVAL 100 // max depth of value stack
  9. #define BUFSIZE 100
  10.  
  11. int sp = 0; // next free stack position
  12. double val[MAXVAL]; // value stack
  13. char buf[BUFSIZE]; // buffer for ungetch
  14. int bufp = 0; // next free position in buffer
  15.  
  16. // get a (possibly pushed back) character
  17. int getch(void){
  18. return (bufp > 0) ? buf[--bufp] : getchar();
  19. }
  20.  
  21. // push character back on input
  22. void ungetch(int c) {
  23. if (bufp >= BUFSIZE)
  24. printf("ungetch: too many characters\n");
  25. else
  26. buf[bufp++] = c;
  27. }
  28.  
  29. // get next operator or operand
  30. int getop(char s[]) {
  31. int i, c;
  32.  
  33. while ((s[0] = c = getch()) == ' ' || c == '\t');
  34. s[1] = '\0';
  35. if (!isdigit(c) && c != '.')
  36. return c; // not a number
  37. i = 0;
  38. if (isdigit(c)) // collect integer part
  39. while (isdigit(s[++i] = c = getch()));
  40. if (c == '.') // collect fraction part
  41. while (isdigit(s[++i] = c = getch()));
  42. s[i] = '\0';
  43. if (c != EOF)
  44. ungetch(c);
  45. return NUMBER;
  46. }
  47.  
  48. // push f onto value stack
  49. void push(double f) {
  50. if (sp < MAXVAL)
  51. val[sp++] = f;
  52. else
  53. printf("error: stack full, can't push %g\n", f);
  54. }
  55.  
  56. // pop and return top value from stack
  57. double pop(void) {
  58. if (sp > 0)
  59. return val[--sp];
  60. else {
  61. printf("error: stack empty\n");
  62. return 0.0;
  63. }
  64. }
  65.  
  66. // Reverse Polish calculator
  67. main() {
  68. int type;
  69. double op2;
  70. char s[MAXOP];
  71.  
  72. while ((type = getop(s)) != EOF) {
  73. switch (type) {
  74. case NUMBER:
  75. push(atof(s));
  76. break;
  77. case '+':
  78. push(pop() + pop());
  79. break;
  80. case '*':
  81. push(pop() * pop());
  82. break;
  83. case '-':
  84. op2 = pop();
  85. push(pop() - op2);
  86. break;
  87. case '/':
  88. op2 = pop();
  89. if (op2 != 0.0)
  90. push(pop() / op2);
  91. else
  92. printf("error: zero divisor\n");
  93. break;
  94. case '\n':
  95. printf("\t%.8g\n", pop());
  96. break;
  97. default:
  98. printf("error: unknown command %s\n", s);
  99. break;
  100. }
  101. }
  102. return 0;
  103. }
Add Comment
Please, Sign In to add comment