【问题标题】:Evaluating Postfix Expression using stack and array of char with C++使用 C++ 使用堆栈和 char 数组评估后缀表达式
【发布时间】:2013-10-11 10:58:29
【问题描述】:

我不知道我哪里做错了。每次我在 main 函数的末尾“弹出”它总是什么也没给我。我在每次操作后推送之前和之后都通过弹出来检查,结果就在那里。但是每次我跳出 for 循环时,堆栈什么也没给我。之前谢谢,非常感谢您的回答。 P.S = 我不允许使用类或 OOP。所以请不要用那些方法给我答案。

#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<cstdlib>
#include<cstring>

using namespace std;

typedef struct
{
    int top;
    int data[20];
}stack;

void initStack(stack &S)
{
     int i;
     S.top=-1;
}

int pop (stack &S)
{
    int number;
    number = S.data[S.top];
    S.top = S.top - 1;
    return number;
}

void push(stack &S, int number)
{
    S.top = S.top + 1;
    S.data[S.top] = number;
}

void compute(stack &S, char *ch, int n)
{
    int result;
    for (int i = 0 ; i <= n-1; i++)
    {
        if (ch[i] == '*')
        {
            int operand1 = pop (S);
            int operand2 = pop (S);
            result = operand1 * operand2;
            push(S, result);
        }

        else if (ch[i] == '/')
        {
            int operand1 = pop (S);
            int operand2 = pop (S);
            result = operand1 / operand2;
            push(S, result);
        }

        else if (ch[i] == '+')
        {
            int operand1 = pop (S);
            int operand2 = pop (S);
            result = operand1 + operand2;
            push(S, result);
        }

        else if (ch[i] == '-')
        {
            int operand1 = pop (S);
            int operand2 = pop (S);
            result = operand1 - operand2;
            push(S, result);
        }

        else
        {
            result = ch[i] - '0';
            push(S, result);
        }
    }
}

main()
{
    stack ST;
    char ch[20];
    initStack(ST);
    cout<<"Please enter the operation: ";
    gets(ch);
    int n = strlen(ch);
    compute(ST, ch, n);
    pop(ST);
}

【问题讨论】:

  • 你从来没有真正“弹出”main 函数,也没有打印任何东西,那么你怎么知道有问题?
  • 我不小心忘记了在stackoverflow中编写的脚本中弹出,但是如果我将弹出添加到其中,它不会改变任何东西。
  • 那么请将问题中的代码编辑为您实际遇到问题的代码。
  • 好的,我已经编辑了代码。之前感谢您的回复:)

标签: c++ arrays char stack postfix-notation


【解决方案1】:

好吧,如果我理解正确,那么问题是一个非常简单的问题。你需要打印你弹出的值

替换

pop(ST);

与

cout << pop(ST) << '\n';

很明显,除非你记得打印你想看到的东西,否则你什么都看不到。

【讨论】:

  • 我想我太专注于算法然后我忘了添加 cout,现在它可以工作了。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 2014-07-01
  • 2020-07-15
  • 2011-08-03
  • 2012-05-01
  • 2013-05-02
  • 2018-09-28
  • 1970-01-01
相关资源
最近更新 更多