0

我正在用 C 做家庭作业。我必须构建一个计算器来接收 RPN,将其转换为双精度数,从堆栈中添加/删除它并打印堆栈上剩余的内容。在我运行它之前,一切似乎都很顺利。输入我的输入后,char[] 成功转换为 double(或者我认为是这样),并且在此过程中的某个地方(可能在 getop() 中)程序是否认为我没有输入数字。这是代码和输出。

#include <stdio.h>

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

int getOp(char []); /* takes a character string as an input */
void push(double); 
double pop(void);
double asciiToFloat(char []);

/* reverse polish calculator */
int main()
{

    int type;
    double op2;
    char s[MAXOP];

    printf("Please enter Polish Notation or ^d to quit.\n");
    while ((type = getOp(s)) != EOF) {
        switch (type)   {
        case NUMBER:
            push(asciiToFloat(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%.2f\n", pop()); /* this will print the last item on the stack */ 
            printf("Please enter Polish Notation or ^d to quit.\n"); /* re-prompt the user for further calculation */
            break;
        default:
            printf("error: unknown command %s.\n", s);
            break;
        }
    }
    return 0;   
}

#include <ctype.h>

/* asciiToFloat: this will take ASCII input and convert it to a double */
double asciiToFloat(char s[])
{
    double val;
    double power;

    int i;
    int sign;

    for (i = 0; isspace(s[i]); i++) /* gets rid of any whitespace */
        ;
    sign = (s[i] == '-') ? -1 : 1; /* sets the sign of the input */
    if (s[i] == '+' || s[i] == '-') /* excludes operands, plus and minus */
        i++;
    for (val = 0.0; isdigit(s[i]); i++) 
         val = 10.0 * val + (s[i] - '0'); 
    if (s[i] = '.')
        i++;
    for (power = 1.0; isdigit(s[i]); i++) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10.0;
    }
    return sign * val / power;
}



#define MAXVAL 100  /* maximum depth of value 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; /* take the input from the user and add it to the stack */
        printf("The value of the stack position is %d\n", sp);
    }
    else
        printf("error: stack full, cant push %g\n", f);
}

/* pop: pop and return the top value from the 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;
    int c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.') {
        printf("Neither a digit or a decimal.\n");
        return c;   /* neither a digit nor a decimal */
    }
    i = 0;
    if (isdigit(c)) /* grab the integer */
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.') /* grab the fraction */
                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 buffer */

/* getch: get a number that may or may not have been pushed back */
int getch(void)
{
    return (bufp > 0) ? buf[--bufp] : getchar(); 
}

/* ungetch: if we read past the number, we can push it back onto input buffer */
void ungetch(int c)
{
    if (bufp >= BUFSIZE)
        printf("ungetch: to many characters.\n");
    else
        buf[bufp++] = c;
}

输出 :

请输入波兰表示法或 ^d 退出。123 堆栈位置的值为 1 既不是数字也不是小数。
123.00 请输入波兰表示法或 ^d 退出。

任何关于正在发生的事情的想法都会非常有帮助。似乎数字被正确传递,从char正确格式化为double,然后出现问题。

谢谢你。

岩石

4

2 回答 2

3

改变

        printf("Neither a digit or a decimal.\n");

        printf("Neither a digit or a decimal: %d 0x%x.\n", c, c);

这样您就可以看到导致该消息的原因。

于 2011-10-25T18:36:57.317 回答
0

您的输出显示 getch() 在行尾返回换行符 ("\n", 0x0A)。此外,除非您被要求为家庭作业编写 asciiToFloat(),否则您应该使用标准 C 库中的 atof() 或 strtod()(均在“stdlib.h”中声明)。它们(通常?)被实施以避免在转换过程中损失精度和准确性;重复乘以 10 会导致相同的损失。漂亮的代码,否则!:)

于 2011-10-25T20:26:27.710 回答