gpt4 book ai didi

c - 递归函数 C?

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:46 24 4
gpt4 key购买 nike

为什么这个递归函数有效?我无法理解为什么它不会一直调用自己直到 n=1 然后停止,而不执行低于它调用自己的任何内容。

int main(){
int t[] = {7,9,6,4,2};
int min, max;
search_extremes_rec(t, sizeof(t)/sizeof(t[0]), &min, &max);
printf("min: %d, max: %d", min, max);
return 0;
}
void search_extremes_rec(const int t[], int n, int *min, int *max){
if(n<=1){
*min = t[0];
*max = t[0];
}else{
search_extremes_rec(t, n-1, min, max);
if(*min > t[n-1]){
*min = t[n-1];
}
else if(*max < t[n-1]){
*max = t[n-1];
}
}
}

最佳答案

每当您想了解递归函数的作用时,插入几个打印输出。


void search_extremes_rec(const int t[], int n, int *min, int *max){
printf("Entering search_extremes_rec. n:%d\n", n);
if(n<=1){
printf("Base case. Exiting\n");
*min = t[0];
*max = t[0];
}else{
printf("Calling recursively...\n");
search_extremes_rec(t, n-1, min, max);
printf("Recursive call done. n:%d min:%d max:%d\n", n, *min, *max);

if(*min > t[n-1]){
*min = t[n-1];
}
else if(*max < t[n-1]){
*max = t[n-1];
}
}
}

输出:


$ ./a.out
Entering search_extremes_rec. n:5
Calling recursively...
Entering search_extremes_rec. n:4
Calling recursively...
Entering search_extremes_rec. n:3
Calling recursively...
Entering search_extremes_rec. n:2
Calling recursively...
Entering search_extremes_rec. n:1
Base case. Exiting
Recursive call done. n:2 min:7 max:7
Recursive call done. n:3 min:7 max:9
Recursive call done. n:4 min:6 max:9
Recursive call done. n:5 min:4 max:9
min: 2, max: 9

如您所见,它确实会一直持续到 n=1。

关于c - 递归函数 C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58712718/

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