gpt4 book ai didi

c++ - 这个递归函数在 C++ 中是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 23:25:14 27 4
gpt4 key购买 nike

我目前正在上 C++ 类(class),我们正在学习递归,在类里面,我的教授使用此函数作为递归的示例,该函数旨在返回数字中的最小数字,并且是:

int smallD(int n) {
if (n < 10) return n;
int x = smallD(n / 10);
if (x < n % 10) return x;
else return n % 10;
}

我对将 x 设置为递归调用的工作方式感到困惑,函数是否会在 n < 10 之前一直运行 n/10,我真的不明白这个概念,可以使用一些指针来说明这是怎么回事功能有效。

最佳答案

这里有一些有助于理解递归的东西。添加 print 语句以观察代码,因为它递归地调用自身并传递和“缩进级别”以提供帮助。

采用原始的缩小代码并将其扩展为更具可读性的内容,并向其添加额外的调试信息。

int smallD(int n, const std::string& indent) {

cout << indent << "enter: smallD(n=" << n << ")" << endl;

if (n < 10) {
cout << indent << "n < 10 => returning: " << n << endl;
return n;
}

cout << indent << "about to recurse inovking smallD(" << n / 10 << ")" << endl;
int x = smallD(n / 10, indent+" "); // grow the indent by 2 spaces
cout << indent << "return from recursion, result is: " << x << endl;

cout << indent << "x=" << x << " n=" << n << " n%10=" << n % 10 << endl;

if (x < n % 10) {
cout << indent << "x is less than n%10, returning: " << x << endl;
return x;
}

cout << indent << "x is greater than or equal n%10, returning: " << n%10 << endl;
return n % 10;
}

让我们通过调用 smallD(8942468, "") 来尝试一下

enter: smallD(n=8942468)
about to recurse inovking smallD(894246)
enter: smallD(n=894246)
about to recurse inovking smallD(89424)
enter: smallD(n=89424)
about to recurse inovking smallD(8942)
enter: smallD(n=8942)
about to recurse inovking smallD(894)
enter: smallD(n=894)
about to recurse inovking smallD(89)
enter: smallD(n=89)
about to recurse inovking smallD(8)
enter: smallD(n=8)
n < 10 => returning: 8
return from recursion, result is: 8
x=8 n=89 n%10=9
x is less than n%10, returning: 8
return from recursion, result is: 8
x=8 n=894 n%10=4
x is greater than or equal n%10, returning: 4
return from recursion, result is: 4
x=4 n=8942 n%10=2
x is greater than or equal n%10, returning: 2
return from recursion, result is: 2
x=2 n=89424 n%10=4
x is less than n%10, returning: 2
return from recursion, result is: 2
x=2 n=894246 n%10=6
x is less than n%10, returning: 2
return from recursion, result is: 2
x=2 n=8942468 n%10=8
x is less than n%10, returning: 2 // <== this is the final result

希望这能帮助您理解递归的工作原理。

关于c++ - 这个递归函数在 C++ 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366219/

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