1 //简单计算器 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <ctype.h> 6 #include <string.h> 7 #include <math.h> 8 9 #define MAXOP 100 //max size of operand or operator 10 #define NUMBER '0' //sign of a number was found 11 #define NAME 'n' //sign of a mathfunc was found 12 #define MAXVAL 100 //max size of the stack 13 #define BUFSIZE 100 //buf io 14 15 int sp = 0; //the postion of the stack 16 double val[MAXVAL]; // the stack 17 double variable[26]; //26 a~z 18 void clear(void); 19 20 int getop(char[]); //get operand or operator 21 void push(double); 22 double pop(void); 23 void mathfnc(char[]); //math function 24 25 int main() 26 { 27 int type,var = 0; 28 double op1, op2, v; 29 char s[MAXOP]; 30 31 for (int i = 0; i<26; i++) 32 { 33 variable[i] = 0.0; 34 35 while ((type = getop(s)) != EOF) 36 switch (type) 37 { 38 39 case NUMBER: 40 push(atof(s)); 41 break; 42 case NAME: 43 mathfnc(s); 44 break; 45 case '+': 46 push(pop() + pop()); 47 break; 48 case '-': 49 op2 = pop(); push(pop() - op2); 50 break; 51 case '*': 52 push(pop()*pop()); 53 break; 54 case '/': 55 op2 = pop(); 56 if (op2 != 0.0) 57 push(pop() / op2); 58 else printf("error:zero divisor"); 59 break; 60 case '%': 61 op2 = pop(); 62 if (op2 != 0.0) 63 push(fmod(pop(), op2)); 64 else printf("error:zero divisor"); 65 break; 66 //对栈操作 打印栈顶元素,交换栈值,清空栈 67 case '?': // printf top of element of the stack 68 op2 = pop(); 69 printf(" %.8g", op2); 70 push(op2); 71 break; 72 case 'c': //clear the stack 73 clear(); 74 break; 75 case 's': //swap the top of the stack 76 op1 = pop(); 77 op2 = pop(); 78 push(op2); 79 push(op1); 80 break; 81 case ' ': 82 v = pop(); 83 printf(" %8f ", v); 84 break; 85 case '=': 86 pop(); 87 if (var >= 'A' && var <= 'Z') 88 variable[var - 'A'] = pop(); 89 else 90 printf("error: no variable name"); 91 break; 92 default: 93 if (type >= 'A' || type <= 'Z') 94 push(variable[type - 'A']); 95 else if (type == 'v') 96 push(v); 97 else 98 printf("error:unknown command %s ", s); 99 break; 100 101 } 102 var = type; 103 } 104 return 0; 105 } 106 107 //出入栈函数 108 void push(double f) 109 { 110 if (sp<MAXVAL) 111 val[sp++] = f; 112 else 113 printf("error :stack full,can push %s ", f); 114 } 115 116 double pop(void) 117 { 118 if (sp > 0) 119 return val[--sp]; 120 else 121 printf("error:stack empty"); 122 return 0.0; 123 } 124 125 126 //getop()函数 127 int getch(void); 128 void ungetch(int); 129 130 int getop(char s[]) 131 { 132 int c, i; 133 134 while ((s[0] = c = getch()) == ' ' || c == ' ') 135 ; 136 s[1] = '