0

我正在编写一个程序,将中缀转换为后缀(通过链表实现的堆栈),存储在字符数组中并评估后缀表达式。在转换之前工作正常。

但是当我调用该函数来评估后缀表达式时,它给出了错误的答案。

问题始于 expEvaluator 类的函数 evalPfExpression() 从后缀的字符数组中弹出一个数字。(通过代码中的大写注释突出显示。)

首先它给出了完全错误的数字。但是从每个数字中减去 48 将其固定为单个数字。(注意每个单个数字都添加了 48)。但是对于 2 位或更高的数字,它仍然给出错误的答案。我想这可能与“char”和“int”类型之间的转换有关。

将不胜感激。

#include <iostream>
#include <conio.h>

using namespace std;

////The node of the stack:
class node   
{
 public:
char value;
node* next;
}; 


////The basic stack class:
class stack 
{
 public:
int size;
node* top;
stack() //default constructor for stack
{
    size=0;
    top=NULL;
}

void push(char);
char pop();
char topstack();
void print();
bool isEmpty();
};


//Stack's push function:
void stack::push(char e)
{
node *temp; 
temp =new node;
temp->next = top;
temp->value=e;
top=temp;
size++;
}
//Stack's pop function:
char stack::pop()
{    
char d;
if (isEmpty())
{
    cout<<"\nStack is Empty\n";
    return '!';
}
else
{
    node *temp = top;
    top=top->next;
    d=temp->value;
    delete temp;
    size--;
}
    return d;
}

//Returns a copy of the stack's top element.
char stack::topstack()
{    
if(size==0)
    return '\0';
else
return top->value;
}

//To print the stack's members.
void stack::print()
{    
cout<<"PRINTING STACK\n";
int s=size;
for(int i=0; i<s; i++)
cout<< pop() <<"\n";
}


//Function to determine whether the stack is empty. Returns true for empty.
bool stack::isEmpty()
{
if(size==0)
{
    return true;
}

return false;
}

////Class, the instance of which will convert infix to postfix.
class expEvaluator
{
 public:
char infix[50];
char postfix[50];

int ps; //counter variable to be used for index of the postfix array.
stack s; //The stack through which the operations will be performed.
expEvaluator() //Constructor.
{
    ps=0;
}
bool isOp(char a)//Function to determine whether the character is an operator.
{
    if(a=='+' || a=='-' || a=='*' || a=='/' || a=='^' || a=='%' )
        return true;
    else
        return false;
}
bool precedence(char a, char b)//To determine the precedence of operators. True means 'a' is of same or lower precedence than 'b'.
{
    if(a=='+' || a=='-')
        return true;
    else if (a=='*' || a=='/')
    {
        if(b=='+' || b=='-')
            return false;
        else if(b=='*' || b=='/')
            return true;
    }
}
//The function that will convert the given infix statement to postfix.
void convertToPostfix()
{
    int l=0; //To keep count of the number of characters entered in infix form.

    cout<<"Enter Infix expression: ";
    cin>>infix;

    for(int i=0; infix[i]!='\0'; i++)
    {
        l++;
    }

    for(int i=0; i<l; i++)
    {
        if(infix[i]=='(')
            s.push(infix[i]);
        else if(isOp(infix[i])) //If character at infix[i] is an operator
        {
            while(isOp(s.topstack()) && precedence(infix[i], s.topstack())) //popping operators from stack to postfix array till operator of
            {                                                               //lower precedence is met.
                    postfix[ps]=s.pop();
                    ps++;
            }
        s.push(infix[i]); //then push the operator onto the stack.
        }
        else if(infix[i]==')') //if right bracket encountered.
        {
            while(s.topstack()!='(') //till left bracket is not encountered,
            {
                postfix[ps]=s.pop(); 
                ps++; //keep popping elements to postfix array.
            }
            s.pop(); //pop left bracket when encountered.
        }
        else //if just an operand is encountered.
        {
            postfix[ps]=infix[i]; //copy to postfix array.
            ps++;
        }
    }
    while(!(s.isEmpty())) //When end of array is reached (the previous loop ends only then) and its not empty,
    {
        postfix[ps]=s.pop(); //pop all elements from stack onto the postfix array.
        ps++;
    }
    postfix[ps]='\0';
    cout << "POSTFIX:\n" << postfix;
}

//Function to calculate the result, when two operands and operator are passed to it.
    int calculate(int op1, int op2, char operand)
    {
        if(operand == '+')
        {
             return op1 + op2;
        }
        else if(operand == '-')
        {
            return op1 - op2;
        }
        else if(operand == '*')
        {
            return op1 * op2;
        }
        else if(operand == '/')
        {
            return op1 / op2;
        }
        else if(operand == '%')
        {
            return op1 % op2;
        }
        else if(operand == '^')
        {
            return op1 ^ op2;
        }           
    }

//Function to evaluate the postfix expression:
void evalPfExpression() 
{
    ps = 0;
    while(postfix[ps]!='\0')
    {

        if (!isOp(postfix[ps]))
        {
            s.push(postfix[ps]);
            ps++;
        }
        else if(isOp(postfix[ps]))
        {//******NOT POPPING CORRECT VALUES.******
            int x = s.pop() - 48; //Second operand.
            int y = s.pop() - 48; //First operand.
            cout << "Second operand: "<< x << " First op:" << y << endl;
            int res = calculate(y, x, postfix[ps]);  //The result of two operands calculation
            s.push(res);                             //is returned to the variable 'res' and pushed 
            ps++;                                    //to the stack
        }
    }
    int result = s.pop(); //When '\0' is encountered, loop stops and the final      result is popped
    cout << "\nThe postfix statement evaluates to:\n" << result << endl;
}


};

//////////////////////////////////////////////////////////////////////////////////
int main(void)
{
expEvaluator e1;
e1.convertToPostfix();
e1.evalPfExpression();

getch();
return 0;
}
4

1 回答 1

0

pop() 没有任何问题。它正在弹出你正在推动的东西。问题在于你在推动什么。

  1. 如果您想要大于 255 的值,则必须使用“int”而不是“char”作为节点中的值类型。

  2. 你在推动角色本身,而不是它的价值。例如,你推的是“0”,而不是 0。它们之间的区别是,你猜怎么着?48.

  3. 对于多位数字,您需要将诸如 atoi() 之类的函数的结果推送到要解析为数字的字符串上。

于 2013-10-13T05:06:30.167 回答