我的C程序为什么结果会是6啊!递归调用应该只是返回给倒数第二个调用的函数才对啊!其他的递归调用函数应该是没有接收到返回值才对啊!
#include <stdio.h>
int i = 1;
int fc(int n){
if(n == 1)
return i;
else if(n % 2 == 0) {
fc(n / 2);
i++;
}
else {
fc(3 * n + 1);
i++;
}
}
int main() {
int n, step;
n = 5;
step = fc(n);
printf("\n%d \n", step);
printf("\n%d", i);
return 0;
}
i是全局变量啊
你的fc函数返回值写的是return i
这返回值本来就没有什么意义
而i是在每次执行递归的时候都++的
那么你的函数到底执行了多少次递归,就执行了多少次i++
因为整个过程中除了让i自加,并没有修改i的地方
所以i++写在fc调用之前还是调用之后都是等效的
但i是全局变量啊,在递归过程中,每次递归i值就会增加1
第一次是5,执行fc(3 * n + 1),相当于f(16),后续i会加1
对于f(16),会一直递归执行fc(n/2),直到fc(1)结束递归,返回i,在这个过程中,f(16),f(8),f(4),f(2)各自会让i加1,因此总共i会加5次,因此最后return时,i值是6
我尝试了Javascript -> undefined
var i = 1;
let n = 5;
function fc(n){
if(n == 1)
return i;
else if(n % 2 == 0) {
fc(n / 2);
i++;
}
else {
fc(3 * n + 1);
i++;
}
}
console.log(fc(n))
Python -> None
i = 1
def fc(n):
global i
if n == 1:
return i
elif n % 2 == 0:
fc(n / 2)
i += 1
else:
fc(3 * n + 1)
i += 1
n = 5
step = fc(n)
print("step: {}".format(step))
以及Java -> -1
指定的
package com;
public class testC {
private int i = 0;
public static void main(String[] args) {
testC c = new testC();
int r = c.fc(5);
System.out.println(r);
}
public int fc(int n){
if(n == 1)
return i;
else if(n % 2 == 0) {
fc(n / 2);
i++;
}
else {
fc(3 * n + 1);
i++;
}
return -1;
}
}
我得到了相同的答案,我不清楚为什么C语言
拥有连续递归连续返回函数值的功能