- 论坛徽章:
- 0
|
本帖最后由 lylesong 于 2012-01-18 09:27 编辑
这个是书上的一个例子,是一个逆波兰式计算器,
我把这个例子拿来运行后,最开始发现一旦入栈,马上就又出栈了,后面找了很久,发现每次都会输出换行符 '\n',就会运行switch 里面的 case '\n': 语句,而那里又调用了pop()函数,所以就会导致入栈马上又出栈了,
我注释掉这一段后,在'+'这种情况下运行程序,发现可以得到正确的加法结果,但是在输出中,还是有'\n'这种情况,因为没有了这种case,所以就跳转到default情况里面了,就会导致每次输入,都会有对应default输出,这个问题是怎么回事呢?
我检查了getop()函数,实在找不到问题在哪里,希望大家能帮我分析一下,谢谢 - #include<stdio.h>
- #include<stdlib.h>
- #include<ctype.h>
- #define MAXOP 100
- #define NUMBER '0'
- #define MAXVAL 100
- #define BUFSIZE 100
- int getop(char []);
- void push(double);
- double pop(void);
- int getch(void);
- void ungetch(int);
- int sp = 0;
- double val[MAXVAL];
- int bufp = 0;
- char buf[BUFSIZE];
- int main()
- {
- int type;
- double op2;
- char s[MAXOP];
- while((type = getop(s)) != EOF)
- {
- switch(type)
- {
- case NUMBER:
- push(atof(s));
- printf("now the sp result is:%d\n",sp);
- break;
- case '+':
- push(pop() + pop());
- printf("now the sp result is:%d\n",sp);
- printf("now the + result is:%f\n",pop());
- break;
- case '*':
- push(pop() * pop());
- printf("now the sp result is:%d\n",sp);
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- printf("now the sp result is:%d\n",sp);
- break;
- case '/':
- op2 = pop();
- if(op2 != 0.0)
- push(pop() / op2);
- else
- printf("error:zero divisor\n");
- break;
- //case '\n':
- // printf("\t%.8g\n",pop());
- // printf("now the sp result is:%d\n",sp);
- // break;
- default:
- printf("error:unknown command %s\n",s);
- break;
- }
- }
- return 0;
- }
- void push(double f)
- {
- if(sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error:stack full,can't push %g\n",f);
- }
- double pop(void)
- {
- if(sp > 0)
- return val[--sp];
- else
- {
- printf("error:stack empty\n");
- return 0.0;
- }
- }
- int getop(char s[])
- {
- int i, c;
- while((s[0] = c = getch()) == ' ' || c == '\t')
- ;
- s[1] = '\0';
- if(!isdigit(c) && c != '.')
- return c;
- i = 0;
- if(isdigit(c))
- while(isdigit(s[++i] = c = getch()))
- ;
- if(c == '.')
- while(isdigit(s[++i] = c = getch()))
- ;
- s[i] = '\0';
- if(c != EOF)
- ungetch(c);
- return NUMBER;
- }
- int getch(void)
- {
- return (bufp > 0) ? buf[--bufp] : getchar();
- }
- void ungetch(int c)
- {
- if(bufp >= BUFSIZE)
- printf("ungetch:too many characters\n");
- else
- buf[bufp++] = c;
- }
复制代码 用gdb调试了一下,发现这里的运行过程是这样的,所以我还是无法判断到底哪里出了问题,- (gdb) b 31
- Breakpoint 1 at 0x804856d: file polish.c, line 31.
- (gdb) run
- Starting program: /home/song/cprogram/polish/polish
- 4
- Breakpoint 1, main () at polish.c:32
- 32 push(atof(s));
- (gdb) n
- 33 printf("now the sp result is:%d\n",sp);
- (gdb) n
- now the sp result is:1
- 34 break;
- (gdb) n
- 27 while((type = getop(s)) != EOF)
- (gdb) n
- 29 switch(type)
- (gdb) n
- 61 printf("error:unknown command %s\n",s);
复制代码 |
|