2017-01-03 59 views
-8

我明白这个方法所做的一切,直到m=1n=1if()之后当m=1n=1有问题时会发生什么情况。为什么这个递归方法被认为是一个阶乘?

public class exc { 

    public static void main(String[] args) { 
     System.out.println(prod(1, 4)); 
    } 

    public static int prod(int m, int n) { 

     if (m == n) { 
      return n; 

     } else { 
      int recurse = prod(m, n - 1);      

      int result = n * recurse;  // how n gets its value here? 
      return result; 

     } 
    } 
} 
  1. 什么是递归的价值?我的意思是如何产生只有一个 整数? (因为它有两个整数)

  2. 如果当m = 1且n = 1时返回值为1,那么为什么程序不会在那里终止?而是在“返回结果”之后终止。在其他?

  3. 在m = 1且n = 1之后,n是2(在递归中); n如何设置为2?是否因为2还在记忆中,需要处理?

我检查this page

我也用不同的println行之后看出来说,但没有帮助。我也使用了一个调试器。

+2

如何在调试中运行此操作并查看? – Guy

+1

它被认为是一个阶乘因为它*是*。不清楚你在问什么。 – EJP

+0

[Understanding recursion]可能的重复(http://stackoverflow.com/questions/717725/understanding-recursion)和http://stackoverflow.com/questions/3021/what-is-recursion-and-when-should- i-use-it – Azodious

回答

1

你的程序返回阶乘当m = 1 借此例如:(M = 1,N = 4)

4 != 1 -> so you call recursively prod(1, 3) 
    3 != 1 -> so you call recursively prod(1, 2) 
     2 != 1 -> so you call recursively prod(1, 1) 
      1 == 1 -> you return 1 to the last call 
     In this call, recurse = 1 and n = 2 so you return 2 to the upper call 
    Here, recurse = 2, n = 3, so you return 6 to the upper call 
Here, recurse = 6, n = 4, so you return 24 to the upper call 

END OF FUNCTION, result is 24 which is 4! 

每次被递归调用该函数PROD,当前函数prodA是暂停(将其变量的值保存在内存中)执行新函数prodB,直到prodB将某些内容返回给prodA。然后A继续执行(从内存中加载它的值)