后缀评估,为什么推送函数不更新堆栈变量的顶部?

postfix evaluation , why is the push function not updating the top of stack variable?

当给出输入“53+”时,它正在压入 5 并将 tos 从“-1”更新为 0,但是当第二次调用该函数时,它压入 3 但 tos 仍然是 0,而不是 1。请帮忙

#include<iostream>

using namespace std;

int push(int tos, int x);
int pop(int tos);

int st[50];
int tos=-1;

int main()
{
    char str[30];
    int r,k,v1,v2,i;

    cin>>str;
    for(i=0;str[i]!='[=10=]';i++)
    {
        if(str[i]!='*'&&str[i]!='-'&&str[i]!='+'&&str[i]!='/')
        {
            k=str[i]-'0';
            push(tos,k);
        }
        else
        {
            if(tos==-1||tos==0) 
                cout<<"enter correct format";
            else
            {
                v1=pop(tos);
                v2=pop(tos);
                switch(str[i])
                {
                case '*': r=v1*v2;
                    push(tos,r);
                    break;
                case '+': r=v1+v2;
                    push(tos,r);
                    break;
                case '-': r=v1-v2;
                    push(tos,r);
                    break;
                case '/': r=v1/v2;
                    push(tos,r);
                    break;
                default: 
                    cout<<"invalid";
                }
            }
        }
    }
    r=pop(tos);
    cout<<endl<<r;
    return 0;
}
int push(int tos, int x)
{
    if (tos==50-1)
        cout<<"overflow"<<endl;
    else
    {
        tos++;
        st[tos]=x;
        cout<<endl<<"pushed"<<tos<<st[tos];
    }
}

int pop(int tos)
{ 
    int z;
    if(tos==-1)
        cout<<"underflow";
    else
    {
        z=st[tos];
        tos-=1;
    }
    return z;
}

当给出输入“53+”时,它正在压入 5 并将 tos 从“-1”更新为 0,但是当第二次调用该函数时,它压入 3 但 tos 仍然是 0,而不是 1。

基本问题是您有两个名为 tos.

的变量

首先是这个全局变量。

int tos=-1;
int main()
{

然后在 push 函数

中有另一个名为 tos 的变量
int push(int tos, int x)
{ 

目前您的代码更改了局部变量,但没有更改全局变量,因此造成了混乱。使用相同名称的局部变量和全局变量是自找麻烦。在这种情况下,我建议您删除局部变量。 st 数组作为全局操作,因此 tos 变量相同似乎合乎逻辑。

int push(int x)
{ 

您也必须将每次调用更改为推送

                       push(tos,r);

变成

                       push(r);

等等等

然后您需要对具有完全相同问题的 pop 函数进行完全相同的更改。

您的 push()pop() 函数按值接收 tos,因此它们对 tos 所做的任何更改都不会反映在函数外部。

一种解决方案是通过引用传递 tos,例如

int push(int &tos, int x)
{
    // Any changes to tos are now reflected in the variable passed in.
    ...
}