Topic: 各位高手,这程序怎么执行的?(recursion)

  Print this page

1.各位高手,这程序怎么执行的?(recursion) Copy to clipboard
Posted by: dkber
Posted on: 2005-11-12 10:01

请问下面程序是怎么执行的,谢谢赐教

class Factorial{
  int fact(int n){
        
    int result;
    System.out.println(n);
    if (n==1) return 1;
    result = fact(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));
    System.out.println("Factorial of 4 is "+f.fact(4));
    System.out.println("Factorial of 5 is "+f.fact(5));
  }
}



Use a debugger to follow the flow, or even just add some printlns.

请尽量使用准确的文字描述作为标题

2.Re:各位高手,这程序怎么执行的? [Re: dkber] Copy to clipboard
Posted by: liumiaowilson
Posted on: 2005-11-13 11:19

类似与栈的原理
如fact(3):
fact(3)------print " 3 "
result=3*fact(2)
fact(2)------print "2"
result=3*2*fact(1)
fact(1)-------print"1"
result=3*2*1


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923