【发布时间】:2014-10-12 13:52:54
【问题描述】:
我花了几个小时试图弄清楚为什么即使 return 语句仅在 if(基本情况)内,这个递归函数仍然有效。
#include<stdio.h>
int main( void )
{
int sum_recursive_function( int const number_copy );//function prototype
int number, sum_recursive;
puts( "Please type a number and I will add its digits:" );
scanf( "%d", &number );
sum_recursive = sum_recursive_function( number );
printf( "%s%d\n", "The sum of the digits is: ", sum_recursive );
}
int sum_recursive_function( int const number_copy )
{
int last_digit, sum_pre = 0;
if( number_copy == 0 ){
return sum_pre;
}
else{
last_digit = number_copy % 10;
sum_pre = last_digit + sum_recursive_function( number_copy / 10 );
}
}
我明白这一点:
如果我输入数字 1,函数内部的 if 会检查 number_copy 是否等于 0,如果不是,它会进入 else 语句,然后将 1 除以 10 = 1 的余数分配给 @ 987654326@。 Last_digit (1) 添加了递归调用,将 1/10=0 发送到 sum_recursive_function。这次sum_recursive_function 检查参数是否等于 0,如果等于 0,则返回 sum_pre 为 0。Sum_pre 是 = 1 + 0。然后我不明白 @987654332 是怎么回事@ 将 Sum_pre (1) 返回到 main。
【问题讨论】:
-
如果你不指定返回值并且控制权传递到函数的末尾,许多编译器将返回堆栈中发生的任何内容——在这种情况下,它将是最后计算的值, sum_pre。不过,这是未定义的行为——您应该始终使用 return 语句将值传递到函数之外。