gpt4 book ai didi

c++ - 从递归堆栈帧返回时不保留值?

转载 作者:行者123 更新时间:2023-11-30 00:57:01 25 4
gpt4 key购买 nike

我刚开始学习递归,我被困在一个问题上,该问题涉及在一堆炮弹中找到炮弹的数量,每个级别显然是一个平方数,例如。顶部堆栈是 1,第二个是 4,第三个是 16 等等......

The stack of cannonballs looks conceptually like this

我跟踪了 Xcode 中观察变量值的步骤,我看到的是,当达到基本情况时,“numBalls”是正确的,但是当堆栈帧结束时,该值不会返回并丢失.

我觉得我应该知道如何解决这个问题,但我似乎无法弄清楚。

这是我使用的代码:

#include <iostream>
using namespace std;

int GetCannonballs(int height, int numBalls);
int Cannonballs(int height);

int main(int argc, char *argv[]) {
cout << Cannonballs(3) << endl;
}

int GetCannonballs(int height, int numBalls)
{
if(height <= 0) {
return numBalls;
} else {
return GetCannonballs(height-1, numBalls + (height*height));
}
}

int Cannonballs(int height) // Wrapper function
{
int numBalls = 0;
GetCannonballs(height, 0);
return numBalls;
}

我得到的返回值为0

对于我的错误或误解的任何帮助或解释将不胜感激!

谢谢。

最佳答案

int numBalls = 0;
GetCannonballs(height, 0);
return numBalls;

您忘记将 numBalls 设置为 GetCannonballs 的结果。你需要做的

int numBalls = 0;
numBalls = GetCannonballs(height, 0);
return numBalls;

或者更简洁地说,

return GetCannonballs(height, 0);

请注意,您可以通过为 GetCannonballs 使用默认参数来摆脱包装函数:

int GetCannonballs(int height, int numBalls = 0);

顺便恭喜你写了一个合适的尾递归函数。

关于c++ - 从递归堆栈帧返回时不保留值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9169424/

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