gpt4 book ai didi

java - 陷入递归

转载 作者:行者123 更新时间:2023-12-01 08:03:56 24 4
gpt4 key购买 nike

浏览 Java Complete Reference 我陷入了递归。我打印中间结果来查看值的变化。我可以看到num的值将减少到1并返回1,之后num的值如何增加到3和4?有什么帮助吗?

class Recursion {

public int fact(int num){
int result;

if(num==1){
return 1;
}

System.out.println("Befor fact value of num is: "+num);//here ok!
result=fact(num-1)*num;
System.out.println("After value of num is: "+num); //here not ok!
//System.out.println("result= "+result);
return result;
}
public static void main(String[]args){
Recursion obj=new Recursion();
System.out.println(obj.fact(4));
}
}

最佳答案

您似乎打印了错误的变量,

System.out.println("Before fact value of n is: "+num);//here ok!
result=fact(num-1)*num;
// You didn't change "num".
System.out.println("After value of n is: "+result); //result, not num.
//System.out.println("result= "+result);
return result;

哪个打印

Before fact value of num is: 4
Before fact value of num is: 3
Before fact value of num is: 2
After value of num is: 2
After value of num is: 6
After value of num is: 24
24

关于java - 陷入递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23068380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com