帮忙看下这个java程序输出

来源:百度知道 编辑:UC知道 时间:2024/07/04 19:15:36
public class editplus {
public static void main(String [] args) {
System.out.println("Sum is " + xMethod(5)) ;
}

public static int xMethod(int n) {
if (n==1)
return 1 ;
else
return n + xMethod(n-1);
}
}

输出是sum is 15
为什么呢 主要是这个xMethod是什么意思呢?

xMethod(5) 返回结果为 5 + xMetod(4)
同样 xMethod(4) 又返回为 4 + xMetod(3)
.....

所有综合来说
xMethod(5) 得到的结果为 5 + 4 + 3 + 2 + 1 = 15

Xmethod这个方法就是求1到N的和了,他用的是一种递归的算法。