下面是一个接受int并返回int的函数。在函数内,我调用函数本身,如果i == 1,我想退出函数。
基本上,我试图以递归的方式计算阶乘。
程式码片段
static int factorial(int i){
result = result * i;
if(i==1){
return 0;
}
factorial(i-1);
return 1;
}
注意-result是全局int变量,并初始化为1。
为什么此函数返回1而不是0。[请注意,当i == 1时,使用return语句,指针应从函数中出来]
请不要为阶乘发布更好的算法,我正在寻找-为什么此代码的行为有些不同。
示例调用factorial(3)
:
int i = factorial(3);
+--------------------------------------------------+
|result = result * 3; |
|if (i==1) { |
| // not executed |
|} |
|factorial(2); |
| +-------------------------------------------+ |
| |result = result * 2; | |
| |if (i==1) { | |
| | // not executed | |
| |} | |
| |factorial(1); | |
| | +---------------------------------+ | |
| | |result = result * 1; | | |
| | |if (i==1) { | | |
| | | return 0; | | |
| | |// nothing more in factorial(1) | | |
| | +---------------------------------+ | |
| |// factorial(1) returned 0 (value not used)| |
| |return 1; // factorial(2) | |
| +-------------------------------------------+ |
|// factorial(2) returned 1 (value not used) |
|return 1; // factorial(3) |
+--------------------------------------------------+
i = 1; // the value returned by last call
factorial(3)
返回1!递归已由终止return 0
,但未使用该值
如果最后两行连接到零,则将返回零 return factorial(i-1);
仅factorial(1)
将返回0,例如int i = factorial(1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句