【问题标题】:K&R possible bug in polish calculator波兰语计算器中的 K&R 可能存在错误
【发布时间】:2013-06-14 00:36:12
【问题描述】:

我不知道该在哪里发布,但我想我在 K&R 的波兰语计算器程序中发现了一个相当大的错误。基本上,当您执行操作时,会弹出两个值,而只推送结果。问题是结果没有被推到栈顶!这是一个插图:

教科书提供的波兰语计算器完整代码如下所示:

#include <stdio.h>
#include <stdlib.h> /* for atof() */

#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0' /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);

/* reverse Polish calculator */
main()
{
    int type;
    double op2;
    char s[MAXOP];

    while ((type= getop(s)) != EOF) {
        switch (type) {
        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 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor\n");
            break;
        case '\n':
            printf("\t%.8g\n", pop());
            break;
        default:
            printf("error: unknown command %s\n", s);
            break;
        }
    }
    system("Pause");
    return 0;
}

#define MAXVAL 100 /* maximum depth of val stack */

int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if ( sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full. can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

#include <ctype.h>

int getch(void);
void ungetch(int);

/* getop: get next operator or numeric operand */
int getop(char s[])
{
    int i, c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.')
        return c; /* not a number */
    i = 0;
    if (isdigit(c)) /*collect integer part*/
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.') /*collect fraction part*/
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

int getch(void) /* get a (possibly pushed back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

如果你想自己检查,我所做的只是添加

static int pass = 0;
int i, check;
i = check = 0;

在 main() 和

的 while 循环内
if(!check) {
    printf("pass #%d\n",pass++);
    while(val[i] != '\0') {
        printf("val[%d]: %.2f\n",i,val[i]);
        ++i;
    }
}

在 while 循环结束时,就在 switch 语句之后。我还将check = 1; 放在'\n' 的情况下。

作为一种可能的解决方法,我重新编写了 pop 函数,以便在访问 val 数组时立即从 val 数组中删除弹出的值。所以不是

double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

你会有类似的东西

double pop(void)
{
    if (sp > 0) {
        double temp = val[--sp];
        val[sp] = '\0';
        return temp;
    }
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

我还重新编写了 push 函数以确保始终将值推送到 val 数组的末尾。所以不是

void push(double f)
{
    if ( sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full. can't push %g\n", f);
}

你应该有

void push(double f)
{
    if ( sp < MAXVAL) {
        while (val[sp] != '\0')
            ++sp;
        val[sp++] = f;
    }
    else
        printf("error: stack full. can't push %g\n", f);
}

即使有这些变化,我仍然需要重新编写

case '\n':
        printf("\t%.8g\n", pop());
        break;

要检索堆栈顶部的值而不弹出它,这需要用一个简单的函数替换printf 语句

void print_top(void)
{
    int i = 0;
    while( val[i] != '\0' )
        ++i;
    --i;
    printf("\t%.8g\n",val[i]);
}

只有这样,波兰语计算器才能按预期运行,至少就堆栈在幕后所做的而言。您可以使用修改后的代码自己尝试一下:

#include <stdio.h>
#include <stdlib.h> /* for atof() */
#include <ctype.h>

#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0' /* signal that a number was found */
#define MAXVAL 100 /* maximum depth of val stack */

int getop(char []);
void push(double);
double pop(void);
void print_top(void);

int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */

/* reverse Polish calculator */
main()
{
    int type;
    double op2;
    char s[MAXOP];

    while ((type= getop(s)) != EOF) {

        static int pass = 0;
        int i, check;
        i = check = 0;

        switch (type) {
        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 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor\n");
            break;
        case '\n':
            print_top();
            check = 1;
            break;
        default:
            printf("error: unknown command %s\n", s);
            break;
        }
        if(!check) {
            printf("pass #%d\n",pass++);
            while(val[i] != '\0') {
                printf("val[%d]: %.2f\n",i,val[i]);
                ++i;
            }
        }
    }
    system("Pause");
    return 0;
}

/* push: push f onto value stack */
void push(double f)
{
    if ( sp < MAXVAL) {
        while (val[sp] != '\0')
            ++sp;
        val[sp++] = f;
    }
    else
        printf("error: stack full. can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0) {
        double temp = val[--sp];
        val[sp] = '\0';
        return temp;
    }
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

int getch(void);
void ungetch(int);

/* getop: get next operator or numeric operand */
int getop(char s[])
{
    int i, c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.')
        return c; /* not a number */
    i = 0;
    if (isdigit(c)) /*collect integer part*/
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.') /*collect fraction part*/
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

int getch(void) /* get a (possibly pushed back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
    printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

void print_top(void)
{
    int i = 0;
    while( val[i] != '\0' )
        ++i;
    --i;
    printf("\t%.8g\n",val[i]);
}

请注意,我必须将我的大部分 #define 语句和原型声明移到开头,以适应 main() 末尾的调试 printfstatement。

*编辑了我的一些大胆的主张:P

【问题讨论】:

  • 不。只是堆栈向上增长,即。 e. val[0] 是底部(如果只有一个元素,也是顶部)。而且在你打印结果的时候,val[1]是无效的,已经被弹出了。
  • ` while (val[sp] != '\0')` 看起来不对。
  • 更正:它错了。
  • 哇,昨天你还想弄清楚*ptrptr之间的区别,今天你发布了K&R代码操作中的基本错误K&R 和他们的无数读者都没有发现。这是您今天(以及后天和后天..)的话:谦虚
  • 因为没有一个有能力的 C++ 程序员会努力谦虚地回应尖刻的反馈。如果一个天生的 C++ 程序员问过这个问题,那么现在事情就会着火了......(但说真的,很荣幸能够从容应对反馈 - 希望这是下次的教训)跨度>

标签: c stack calculator polish


【解决方案1】:
  1. 您正在向后考虑堆栈 - 堆栈顶部位于最高有效索引中,而不是 val[0]。当您查看操作数的推送时,这种行为很明显。你的输出:

    3 4 +
    pass #0
    val[0]: 3.00
    pass #1
    val[0]: 3.00
    val[1]: 4.00
    

    首先,3 被推送 - 进入(之前为空的)堆栈的顶部 - 它位于插槽 0 中。下一个 4 被推送。如您所见,它进入了val[1],清楚地表明val[0] 在这种情况下不是堆栈的顶部。

  2. 您打印的堆栈不正确,这让您更加困惑。将您的打印循环更改为:

    while (i < sp) {
        printf("val[%d]: %.2f\n",i,val[i]);
        ++i;
    }
    

    也就是说,只打印堆栈中的有效条目,您会看到错误。

    您当前的比较是在堆栈上寻找0 条目,这不是程序识别空闲条目的方式。这就是 sp 变量的用途。除了寻找错误的东西之外,它还以一种奇怪的方式进行 - val 是一个浮点数数组 - 你为什么要与字符文字 \0 进行比较?

    这是完整的更正输出:

    3 4 +
    pass #0
    val[0]: 3.00
    pass #1
    val[0]: 3.00
    val[1]: 4.00
    pass #2
    val[0]: 7.00
        7
    

    现在,您会看到正确的输出 - 3.004.00 都被弹出,7.00 被推回堆栈。它现在是唯一有效的条目。

【讨论】:

  • 或者-更可能-一些 printf() 调试。
  • 我不确定我是否遵循。我通过提升 OP 的代码并修复它来生成输出。
  • "你为什么要与字符文字 \0 进行比较?" -- 也许 OP 将 \0 的概念过度解释为“终结者”。
  • 与 "\0" 比较是我到达任意长度数组末尾的常用技巧。我想这只适用于字符数组,那么你通常会怎么做才能到达一个 int 数组的末尾?
  • 你知道它有多大并使用计数器。如果您的int 数组中有一个零怎么办?通常,您的技巧也不适用于字符数组 - 仅适用于格式良好的字符串。
【解决方案2】:

不。只是堆栈向上增长,即。 e. val[0] 是底部(如果只有一个元素,也是顶部)。而且在你打印结果的时候,val[1]是无效的,已经被弹出了。

【讨论】:

    【解决方案3】:

    K&R 中给出的反向抛光计算器代码中没有错误。

    仅当输入在一行中时才有效。

    如果按回车,编译器会读取'\n',导致代码为(case '\n':)并调用pop函数。

    代码结果在给定的图像中:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多