dzungchaos

CTDL&TT: Tính toán hậu tố

May 31st, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. //Hau to
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <conio.h>
  6.  
  7. int stack [1000];
  8. int top;
  9.  
  10. // Tính giá tr. c.a bi.u th.c
  11. int eval (char *s);
  12. // Ki.m tra có ph.i phép toán
  13. int isop (char op);
  14. // Thao tác ð.y ra c.a ngãn x.p
  15. int pop (void);
  16. // Thao tác ð.y vào c.a ngãn x.p
  17. void push (int a);
  18. // Th.c hi.n phép toán
  19. int do_op (int a, int b, char op);
  20.  
  21. int main (void){
  22.     char expression[80];
  23.     int value;
  24.    
  25.     printf ("Nhap vao xau bieu thuc: ");
  26.     gets(expression);
  27.     printf ("\nBieu thuc nhap vao: %s", expression);
  28.     value=eval (expression);
  29.     printf ("\nGia tri cua bieu thuc = %i", value);
  30.     getch();
  31.    
  32.     return 0;
  33. }
  34.  
  35. int eval (char *s){
  36.     char *ptr;
  37.     int first, second, c;
  38.     ptr = strtok (s, " ");
  39.     top = -1;
  40.     while (ptr) {
  41.         if (isop (*ptr)) {
  42.         second = pop(); first = pop();
  43.         c = do_op (first, second, *ptr);
  44.         push(c);
  45.         }
  46.         else { c = atoi(ptr); push(c);
  47.         }
  48.     ptr = strtok (NULL, " ");
  49.     }
  50.     return (pop ());
  51. }
  52.  
  53. int do_op (int a, int b, char op){
  54.     int ans;
  55.    
  56.     switch (op) {
  57.         case '+':
  58.         ans = a + b;
  59.         break;
  60.         case '-':
  61.         ans = a - b;
  62.         break;
  63.         case '*':
  64.         ans = a * b;
  65.     break;
  66.     }
  67.    
  68.     return ans;
  69. }
  70.  
  71. int pop (void){
  72.     int ret;
  73.     ret = stack [top];
  74.     top--;
  75.     return ret;
  76. }
  77.  
  78. void push (int a){
  79.     top++;
  80.     stack [top] = a;
  81. }
  82.  
  83. int isop (char op){
  84.     if (op == '+' || op == '-' || op == '*')
  85.         return 1;
  86.     else
  87.         return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment