【问题标题】:How to evaluate a postfix expression using character stack using ASCII conversions如何使用 ASCII 转换使用字符堆栈评估后缀表达式
【发布时间】:2018-09-28 17:02:12
【问题描述】:

代码是使用 ADT 通过包含“stack.h”用户定义的头文件来实现的。

头文件有堆栈操作的代码。 由于不正确的 ASCII 转换,我将输出显示为奇怪的符号。

我应该对代码进行哪些更改才能获得正确的输出。

#include<iostream>
#include<string.h>
#include "stack.h"
using namespace std;

void posteva(char postfix[])
{
    stack s;
    int i=0;
    while(postfix[i]!='\0')
    {
        char x=postfix[i];
        if(isdigit(x))
        {
            s.push(x);
        }
        else
        {
            int op1=s.pop();
            int op2=s.pop();
            int res;
            switch(x)
            {
                case '+':
                    res=op1+op2;
                    break;
                case '-':
                    res=op1-op2;
                    break;
                case '*':
                    res=op1*op2;
                    break;
                case '/':
                    res=op1/op2;
                    break;
                case '%':
                    res=op1%op2;
                    break;  
                case '^':
                    res=op1^op2;
                    break;              
            }
            s.push(res);
        }
        i++;
    }
    cout<<"\n\nRESULT :"<<s.pop();
}

int main()
{
    char postfix[20];
    cout<<"\n\nEnter the postfix : ";
    cin>>postfix;
    posteva(postfix);   
}

【问题讨论】:

  • 例如。我将后缀表达式输入为“23+”,结果是“e”。
  • 这是您提供的 only 输入吗? stack 存储什么? int 值?如果一个操作产生的值大于9,会发生什么?
  • ASCII'2''3' 值分别为 505150 + 51101,恰好是 'e' 的 ASCII 值。

标签: c++ stack postfix-notation


【解决方案1】:

您的代码的问题是您将数字作为字符推送(这没关系),但您使用它们就像它们是ints。如果您只想在堆栈中保留字符,则需要在进出时执行转换:

int op1=s.pop() - '0';
int op2=s.pop() - '0';
...
s.push(res + '0');

这种方法是有问题的,因为您没有简单的方法来处理多位数字。您最好将堆栈转换为整数堆栈,并修改您的代码以处理多位输入。

注意:^ 是 XOR,是按位运算。由于所有其他运算都是算术运算,我想您希望'^' 表示将op1 提高到op2 的幂。在这种情况下,您应该使用数学库中的pow 函数。

【讨论】:

  • 我执行了转换,但它正在为结果工作9。
  • 这就是我在以“这种方法有问题......”开头的段落中解释的内容
  • 那么我没有办法使用字符堆栈来获得正确的结果吗?
  • @NirajWagh 有,但它非常类似于将方形钉子锤入圆孔。
【解决方案2】:

'2''3'ASCII 值分别为 505150 + 51101,恰好是 'e' 的 ASCII 值。

您添加的是 ASCII 编码 值而不是数字。

要将数字转换为其等效的int,请再次查看ASCII table。当谈到数字时,你没有看到一些模式吗?尝试做例如'3' - '0' 看看你得到了什么。

当你得到它时,你就会有你的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 2011-12-14
    • 2013-10-11
    • 2012-05-01
    • 2013-05-02
    • 2020-07-15
    • 2012-09-22
    • 2011-08-03
    相关资源
    最近更新 更多