【问题标题】:Stacks - Evaluating Postfix Expressions in CStacks - 在 C 中评估后缀表达式
【发布时间】:2016-08-16 17:52:03
【问题描述】:

我的任务是实现 int isOperator(char *); 操作数被推送,操作符被置顶,弹出,表达式被推送。

  Example:
  6 5 2 3.14 + 8 * + 3 + *
  Pushing: 6.000000  
  Pushing: 5.000000
  Pushing: 2.000000
  Pushing: 3.140000
  Pushing: 2.000000+3.140000=5.140000

我的实现有问题吗? 这是我的 intOperator(char*)。

int isOperator(char *s){

int i;
char Ops[] = { '+', '-', '*', '/' };

for (i = 0; i < 4; i++)
{
    if (s == Ops[i])
        return (1);
    return (0);
}
}

这是我推送和弹出操作数和运算符的实现。

    S = CreateStack();
n = sizeof(postfixExpression) / sizeof(postfixExpression[0]); // Compute array size
for (i = 0; i<n; i++){ // Print elements of postfix expressions
    printf("%s ", postfixExpression[i]);
}
printf("\n");

for (i = 0; i<n; i++){

    if (isalnum(postfixExpression[i])){
        Push(atof(postfixExpression[i]), S);
        printf("Pushing: %d", atof(postfixExpression[i]));
    }
    else if (isOperator(postfixExpression[i]))
    {
        rightOperand = Top(S);
        Pop(Top(S));
        leftOperand = Top(S);
        Pop(Top(S));

        switch (isOperator(postfixExpression[i])){
        case '+':
            Push(leftOperand + rightOperand, S);
            printf("Pushing: %d+%d=%d", leftOperand, rightOperand, leftOperand + rightOperand);
            break;
        case '-':
            Push(leftOperand - rightOperand, S);
            printf("Pushing: %d-%d=%d", leftOperand, rightOperand, leftOperand - rightOperand);
            break;
        case '*':
            Push(leftOperand * rightOperand, S);
            printf("Pushing: %d*%d=%d", leftOperand, rightOperand, leftOperand * rightOperand);
            break;
        case '/':
            Push(leftOperand / rightOperand, S);
            printf("Pushing: %d/%d=%d", leftOperand, rightOperand, leftOperand / rightOperand);
            break;
        default:
            break;
        }

    }
    else
        break;
}

printf("%s\n", S);
DisposeStack(S);
return 0;

【问题讨论】:

  • isOperator 函数应该会给你编译器警告。阅读它们。检查警告所在行的代码。尝试了解您收到警告的原因。
  • 另外,试着按照函数中循环中的代码,它是做什么的?它会检查所有可能的运算符吗?
  • if (s == Ops[i]) --> if (*s == Ops[i]), if (isalnum(postfixExpression[i])){ --> if (isdigit(*postfixExpression[i])){
  • switch (isOperator(postfixExpression[i])){ --> switch (*postfixExpression[i]){ : isOperator(postfixExpression[i]) return 1 or 0

标签: c stack postfix-notation


【解决方案1】:

一个更简单的实现是这样的:

int isOperator(char *s)
{
    return strchr("+-*/", s[0]) && s[1] == '\0';
}

如果s 中的第一个字符是运算符,第二个字符是空终止符,则返回 1 (true)(表示运算符字符后面没有其他内容,用于严格检查)。

至于栈逻辑,你要确保栈在弹出的时候不为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2014-07-01
    相关资源
    最近更新 更多