> 文档中心 > 100 Days of Code-day29(逆波兰,your bro is coming)

100 Days of Code-day29(逆波兰,your bro is coming)


编写程序 expr,它从命令行计算逆波兰表达式,其中每个运算符或操作数是一个单独的参数。

#define _CRT_SECURE_NO_WARNINGS#include#include#include#include#define MaxOp 100#define number '0'#define MaxRawNum 100char getop(char *);void push(double);double pop(void);double myatof(char *);int main(){int argc;char s[MaxOp],*argv[MaxRawNum];double num, op;char **temp = argv;void ungets(char[]);scanf("%d", &argc);for (int i = 1; i < argc; i++) {argv[i] = (char *)malloc(MaxRawNum * sizeof(char));scanf("%s", argv[i]);}while (--argc > 0){//ungets(" ");ungets(*++temp);//上面运用ungets的目的是想直接读取之前scanf函数捕获到的字符串中//也就是说将它们现房到缓存区buf中,再对其进行读取//而不是用getch中的getchar函数来直接读取输入内容//ungets(" ");该语句是因为每次getop读取数字时,为了确定所读取数字的完整性//所以在每次读取数字之前事先放入一个空格符,这样可以在不读取新的输入内容时//还可以保证getop函数的正常运作//不过在该程序中,该语句可以省略,因为scanf遇到空格符、换行符就会停止读取//也就是说即使是在缓存区中无任何内容,在输入内容中有一个换行符//在第一次读取完数字之后,该换行符就会被压入缓存区//之后它就一直待在缓存区,也就是说不用担心因为多读取字符而导致getop函数无法运行的问题switch (getop(s)){case number:push(atof(s));break;case '+':num = pop() + pop();push(num);break;case '-':op = pop();num = pop() - op;push(num);break;case '*':num = pop() * pop();push(num);break;case '/':op = pop();if (op != 0.0) {num = pop() / op;push(num);}elseprintf("error: zero divisor\n");break;//case '\n'://printf("%f\n", pop());//break;//不需要捕获到换行符之后,再输出内容default:printf("error: unknown command %s\n",s);argc = 1;break;}}printf("\t%.8g\n", pop());return 0;}double myatof(char *s){int sign;double num, pow;num = 0.0;pow = 1.0;sign = (*s == '-') ? -1 : 1;while (isdigit(*s)){num = 10.0 * num + *s - '0';}if (*s == '.')s++;while (isdigit(*s)){num = 10.0 * num + *s - '0';pow *= 10.0;}num = sign * num / pow;return num;}#define MaxVal 100double operand[MaxVal];int place = 0;void push(double op){//注意限定的范围if (place < MaxVal)operand[place++] = op;else {printf("the stack of operand is full, can't push");return;}}double pop(void){//注意限定范围if(place > 0)return operand[--place];else{printf("the stack is empty,can't pop\n");return 0.0;}}char getch(void);void ungetch(char);char getop(char *s){char c;while ((*s = c = getch()) == ' ' || c == '\t');*(s+1) = '\0';if (!isdigit(c) && c != '.')return c;if (isdigit(*++s = c = getch()))//整数部分;if (c == '.')while(isdigit(*++s = c = getch()))//小数部分;if (c != EOF)ungetch(c);*s = '\0';return number;}void ungets(char s[]){void ungetch(char);int len = strlen(s);while (len > 0)ungetch(s[--len]);}#define MaxSize 100char buf[MaxSize];char *bufp = buf;//buf的下一个空闲位置char getch(){return (bufp > buf) ? *--bufp : getchar();}void ungetch(char c){if (bufp < buf + MaxSize){*bufp = c;bufp++;}elseprintf("there is no space in buffer\n");}

100 Days of Code-day29(逆波兰,your bro is coming) 创作打卡挑战赛 100 Days of Code-day29(逆波兰,your bro is coming) 赢取流量/现金/CSDN周边激励大奖