rpn.c (1391B)
1#include <stdint.h> 2#include <stdio.h> 3#include <ctype.h> 4 5#define MAXOP 40 6#define NUMBER '0' 7#define STACKSIZE 40 8 9uint8_t sp; 10int16_t stack[STACKSIZE]; 11 12char s[MAXOP]; 13uint8_t pos; 14int16_t n; 15 16void push(int16_t l) 17{ 18 if(sp < STACKSIZE) 19 stack[sp++] = l; 20 else 21 puts("Stack full"); 22} 23 24int16_t pop(void) 25{ 26 if(sp > 0) 27 return stack[--sp]; 28 else 29 puts("Stack empty"); 30 return 0; 31} 32 33int16_t top(void) 34{ 35 if(sp > 0) 36 return stack[sp-1]; 37 else 38 puts("Stack empty"); 39 return 0; 40} 41 42int8_t read_op(void) 43{ 44 if(pos == 0) { 45 gets(s); 46 } 47 48 while(s[pos] == ' ' || s[pos] == '\t') 49 pos++; 50 51 if(s[pos] == '\0') { 52 pos = 0; 53 return('\n'); 54 } 55 56 if(!isdigit(s[pos])) 57 return(s[pos++]); 58 59 n = s[pos] - '0'; 60 while(isdigit(s[++pos])) 61 n = 10 * n + s[pos] - '0'; 62 63 return NUMBER; 64} 65 66void main(void) 67{ 68 int8_t type; 69 int16_t op2; 70 71 puts("RPN Calculator"); 72 sp = 0; 73 pos = 0; 74 75 while((type = read_op()) != 0) { 76 switch(type) { 77 case NUMBER: 78 push(n); 79 break; 80 case '+': 81 push(pop() + pop()); 82 break; 83 case '*': 84 push(pop() * pop()); 85 break; 86 case '-': 87 op2 = pop(); 88 push(pop() - op2); 89 break; 90 case '/': 91 op2 = pop(); 92 if(op2 != 0) 93 push(pop() / op2); 94 else 95 puts("Divide by 0"); 96 break; 97 case '\n': 98 printf("==> %d\n", top()); 99 break; 100 } 101 } 102}