[Exercise] Exercise 5-10 program expr 2 3 4 + * page 118

User avatar

Topic author
BJT
Site Admin
Site Admin
Posts: 141
Joined: Thu Apr 20, 2017 4:43 pm
Instruction: University Student
Gender:
Age: 27
Venezuela

Exercise 5-10 program expr 2 3 4 + * page 118

Post by BJT » Sat May 06, 2017 12:49 am

Exercise 5-10. Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument. For example,
expr 2 3 4 + *
evaluates 2 * (3+4).


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. #define NUMBER '0'/* signal that a number was found */
  6.  
  7. void push(double);
  8. double pop(void);
  9.  
  10. //pop and push
  11. #define MAXVAL 100 /* maximum depth of val stack */
  12. int sp = 0; /* next free stack position */
  13. double val[MAXVAL]; /* value stack */
  14.  
  15. int main (int argc, char* argv[])
  16. {
  17.     int type;
  18.     double op2;
  19.     while(--argc>0)
  20.     {
  21.         ++argv;
  22.         if (isdigit(**argv))
  23.             type=NUMBER;
  24.         else
  25.             type=**argv;
  26.  
  27.         switch (type)
  28.         {
  29.             case NUMBER:
  30.                 push(atof(*argv));
  31.                 break;
  32.             case '+':
  33.                 push(pop() + pop());
  34.                 break;
  35.             case '*':
  36.                 push(pop() * pop());
  37.                 break;
  38.             case '-':
  39.                 op2 = pop();
  40.                 push(pop() - op2);
  41.                 break;
  42.             case '/':
  43.                 op2 = pop();
  44.                 if (op2 != 0.0)
  45.                     push(pop() / op2);
  46.                 else
  47.                     printf("error: zero divisor\n");
  48.                 break;
  49.             default:
  50.                 printf("error: unknown command %s\n", *argv);
  51.                 break;
  52.         }
  53.     }
  54.  
  55.     printf("\t%.8g\n", pop());
  56.     return 0;
  57.  
  58.     return EXIT_SUCCESS;
  59. }
  60.  
  61. /* push: push f onto value stack */
  62. void push(double f)
  63. {
  64.     if (sp < MAXVAL)
  65.         val[sp++] = f;
  66.     else
  67.         printf("error: stack full, can't push %g\n", f);
  68. }
  69.  
  70. /* pop: pop and return top value from stack */
  71. double pop(void)
  72. {
  73.     if (sp > 0)
  74.         return val[--sp];
  75.     else
  76.     {
  77.         printf("error: stack empty\n");
  78.         return 0.0;
  79.     }
  80. }

input (at the nix system shell use * as multiplier, you must pass it like '*')

Code: Select all

2 3 4 + '*'
output

Code: Select all

14
word count: 251

Link:
BBcode:
HTML:
Hide post links
Show post links

Who is online

Users browsing this forum: No registered users and 2 guests