在java中使用递归调用必须使用if分支语句吗? 为什么不用就报错,用了就好?(新人,求前辈解答)
public static void main(String[] args){
int sun=0;
sun = fun(100);
System.out.println(sun);
} public static int fun(int temp){
if(temp==1){
return 1;
}else
return temp+fun(temp-1);
}能运行
public static void main(String[] args){
int sun=0;
sun = fun(100);
System.out.println(sun);
} public static int fun(int temp){
         return temp+fun(temp-1);
}这样就不行了 

解决方案 »

  1.   

    temp==1是中止程序的条件,如果没有这个条件程序会一直运行,抛出java.lang.StackOverflowError异常。100+fun(99)  99+fun(98)  98+(97) ... 1+(0)  0+(-1)  ...一直到栈溢出。跟有没有if分支语句没关系,用do...while当然也可以,主要是设置程序中止的条件。
      

  2.   

    呃,这个递归要有一个原始解得,也就是当参数满足一定条件时要跳出递归(if n == 1 return 1),不然就无限循环了...