[英]When I use "n--" instead of "n-1" why do I get stackoverflow error?
[英]Why do I need to mention the method name? Why not simply (n-1)*n?
這是示例代碼,我在Java完整參考,第9版中遇到了。
// A simple example of recursion.
class Factorial { // this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n; //This is my question, why not just (n-1)*n?
return result;
} }
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3)); //
} }
因為否則它將不會再次調用該函數,而只會計算n*(n-1)
並退出。 對於3
這將執行3x2=6
,實際上等於3!
。 但是,如果您嘗試使用4!
,那么您的更改將返回4x3=12
,實際上是計算4!
它應該算出4x3x2x1=24
。
答案非常簡單,因為大多數基於遞歸方法的階乘算法都意味着(n -1) * n
調用自身,如果write (n -1) * n
只會相乘一次,結果將是錯誤的(不是n!
)。 關於遞歸方法,尤其是階乘如何工作的文章很多。 例如,閱讀以下內容: https : //www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursive-factorial https://introcs.cs.princeton.edu/java/23recursion/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.