我知道这里有很多关于递归的问题和答案,但请听我说。在我的程序中,我试图得到一个只有偶数的范围。用户输入两个介于 -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
我知道这与将所有这些语句“从堆栈中弹出”有关。问题是我所做的所有研究都给了我解释,假设一个人真正理解递归,而我是一个业余爱好者。谁能帮忙用英文解释一下?