我知道练习4-11还有一个主题,但不同的是,我解决了这个问题,我只需要一些关于我的解决方案的反馈。因此,我将解释它如何在“34 +\n”这样的输出上工作。静态变量c被值‘’初始化,因此第一个if语句的条件计算为true,if语句中的while循环将运行到c到达'3‘为止。因为它是一个数字,函数将返回数字信号,变量c将得到‘’--在第三个if语句中中断循环的值。
现在,在第一个if语句上,我们再次表示,c具有‘’的值。条件被求值为true,if语句中的循环将运行,直到c达到'4‘值为止。同样,因为'4‘是一个“数字”,函数将返回数字信号,而c将得到'+’值--在第三个if语句中中断循环的值。
这一次c等于'+‘,第一个if语句的条件被求值为false,因此值'+’将被返回。我将变量c的值保存在临时变量tmp中,并在将其更改为“”之前用c值初始化tmp。
如果没有这个动作,我会得到一个无限的循环。
该程序由五个部分组成:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
#define MAXOP 1001
int main() {
char entry;
char s[MAXOP];
double op2;
while((entry = getop(s)) != EOF) {
switch(entry) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() +pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if(op2) {
push(pop() / op2);
}
else {
printf("can't divide by 0");
}
break;
case '\n':
printf("The value is: %f \n", pop());
break;
default:
printf("Unrecognized command %s\n", s);
break;
}
}
return 0;
}getch.c
#include <stdio.h>
#define MAXBUF 100
static char buf[MAXBUF];
static int bufp = 0; /* next free position in buffer */
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if(bufp < MAXBUF) {
printf("ungetch has been called\n");
buf[bufp++] = c;
}
else {
printf("the buffer is full\n");
}
}stack.c
#include <stdio.h>
#define MAXSTACK 100
static double stack[MAXSTACK];
static int sp = 0; /* next free position in stack */
void push(double f) {
if(sp < MAXSTACK) {
printf("\t--> the value %f has been pushed\n", f);
stack[sp++] = f;
}
else {
printf("error: the stac is full\n");
}
}
double pop(void) {
if(sp > 0) {
return stack[--sp];
}
else {
printf("error: the stack is empty!\n");
return 0.0;
}
}calc.h
#define NUMBER '0'
#define MAXLINE 1000
/*stack related functions */
void push(double f);
double pop(void);
/* output */
int getch(void);
void ungetch(int c);
/* filtration fuctions */
int getop(char s[]);和getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
int getop(char s[]) {
int i, tmp;
static int c = ' ';
if((s[0] = c) == ' ' || c == '\t') {
while((s[0] = c = getch()) == ' ' || c == '\t')
;
}
s[1] = '\0';
if(!isdigit(c) && c != '.') {
tmp = c;
c = ' ';
return tmp;
}
i = 0;
if(isdigit(c)) {
while(isdigit((s[++i] = c = getch())))
;
}
if(c == '.') {
while(isdigit((s[++i] = c = getch())))
;
}
s[i] = '\0';
return NUMBER;
}发布于 2014-01-14 22:50:38
仅对getop()的评论:
初始循环重复两次退出条件。它(和后续代码)还包含双重赋值,这些赋值是不必要的,通常更好地避免:
if((s[0] = c) == ' ' || c == '\t') {
while((s[0] = c = getch()) == ' ' || c == '\t')
;
}下面是一个更简单的版本:
while (c == ' ' || c == '\t') {
c = getch();
}
s[0] = c;您的循环读取一个数字是重复和重复通常是不可取的。可以将循环提取为一个函数并调用两次:
static int get_number(char *s)
{
int c = getch();
for (; isdigit(c); c = getch()) {
*s++ = c;
}
*s = '\0';
return c;
}在文件结束时,返回EOF。
请注意,您可能应该处理"1.2.3“之类的无效输入。
在main中
char entry;
...
while((entry = getop(s)) != EOF) {entry真的应该是int
https://codereview.stackexchange.com/questions/39081
复制相似问题