/*比如:计算1~5的和
1+2+3+4+5
*/
/*比如:计算1~5的和 1+2+3+4+5 */ public static void main(String[] args) { int n = 4; int revalue = sum(n); int add; System.out.println(revalue); //15 } public static int sum(int n ){ if(n == 1){ return 1; } int revalue = sum(n -1); int result = n+ revalue; return result; }
精简版本
public static void main(String[] args) { int n = 4; int revalue = sum(n); int add; System.out.println(revalue); //15 } public static int sum(int n ){ if(n == 1){ return 1; } int revalue = sum(n -1); int result = n+ revalue; return result; }