gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:21 25 4
gpt4 key购买 nike

当给出输入“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]!='\0';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。

最佳答案

你的 push()pop()函数接收 tos按值,所以他们对 tos 所做的任何更改不反射(reflect)在功能之外。

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

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

关于c++ - 后缀评估,为什么推送函数不更新堆栈变量的顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com