方法一:
package com.smbea.demo; public class Student { private int sum = 0; /** * 递归求和 * @param num */ public void sum(int num) { this.sum += num--; if(0 < num){ sum(num); } else { System.out.println("sum = " + sum); } } }
方法二:
package com.smbea.demo; public class Test { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.sum(); } public static int sum(int num){ if(1 == num){ return 1; } else { return num + sum(num - 1); } }; }
当然还有其它方法,如采用 for 循环、while 循环等,那就不属于递归了!这里就不做讨论了。
时间: 2024-12-26 20:11:13