我知道这里有很多关于递归的问题和答案,但请听我说。在我的程序中,我试图得到一系列只有偶数。用户输入-5000到5000之间的两个数字;如果数字出现故障(即首先输入的数字越大),数字就会被换成顺序;在递归函数中,一个简单的函数返回0或1,使用n%2
确定当前值是偶数还是奇数。问题是我无法弄清楚如何实际使用递归。
int recursive_function(int first_number, int second_number)
{
printf("\n Entering sum function for range %d to %d",
first_number, second_number);
if(first_number > second_number)
return 1;
else
{
if(is_even(first_number) == 0)
{
printf("\n Adding: %d", first_number);
return (first_number += recursive_function(first_number + 1, second_number));
printf("\nThis equals added");
}
else
{
printf("\n Skipping: %d", first_number);
return (first_number += recursive_function(first_number + 1, second_number));
printf("\nThis equals skipped");
}
}
}
程序工作,就递归终止而言,我只是不明白我应该如何弹出堆栈的其余部分。这是一个应该是输出的表示。 (假设值为10和20)
Processing the range 10 to %20:
Entering the sum function for range 10 to 20
Adding: 10
Entering the sum function for range 11 to 20
Skipping: 11
Entering the sum function for range 12 to 20
Adding: 12
Entering the sum function for range 13 to 20
Skipping: 13
Entering the sum function for range 14 to 20
Adding: 14
Entering the sum function for range 15 to 20
Skipping: 15
Entering the sum function for range 16 to 20
Adding: 16
Entering the sum function for range 17 to 20
Skipping: 17
...
Entering the sum function for range 20 to 20
Adding: 20
Entering the sum function for range 21 to 20 (recursion stops here)
(This next part is where I don't know how this happens)
Exiting sum function for range 21 to 20 with result: 0
Exiting sum function for range 20 to 20 with result: 20
Exiting sum function for range 19 to 20 with result: 20
Exiting sum function for range 18 to 20 with result: 38
Exiting sum function for range 17 to 20 with result: 38
Exiting sum function for range 16 to 20 with result: 54
....
Exiting sum function for range 11 to 20 with result: 80
Exiting sum function for range 10 to 20 with result: 90
The sum of all even numbers in the range 10 to 20 is: 90
我知道这与从堆栈中弹出所有这些语句有关。问题是我所做的所有研究都给出了解释,假设一个人真正理解递归,而我是一个业余爱好者。任何人都能用英语帮忙解释一下吗?
答案 0 :(得分:1)
要了解发生的事情,请记下一张纸上的一系列电话。使用较小的范围,比如说18到20。
这是一个例子。我省略了大多数函数体留下行与递归调用。
recursive_function(18, 20): <<< initial call, depth 0
printf("\n Entering
...
printf("\n Skipping: %d", 18); <<< Execution goes to this
return (18 += recursive_function(19, 20)): <<< recurses, depth 1
printf("\n Entering
...
printf("\n Adding: %d", 19);
return (19 += recursive_function(20, 20)): <<< depth 2
printf("\n Entering
...
printf("\n Skipping: %d", 20);
return (20 += recursive_function(21, 20)): <<< depth 3
printf("\n Entering
...
if(21 > 20)
return 1; <<< end of recursion
printf("\nThis equals skipped"); <<< left over at depth 2
printf("\nThis equals added"); <<< left over at depth 1
printf("\nThis equals skipped"); <<< left over at depth 0
现在,您可以按顺序收集所有printf语句并获得结果输出。请注意,在您的代码中,您跳过了“退出...”部分,而输出则包含它。
弹出堆栈。弹出堆栈是由编译器为您完成的。它在函数返回时发生。你应该担心在适当的时候返回,而不是如何弹出堆栈。