package cn.itcast_02;/* * 需求:請用代碼實現求5的階乘 * 下面的知識要知道: * 5! = 1*2*3*4*5 * 5! = 5*4! * * 有幾種方案實現呢? * A:循環實現 * B:遞歸實現 * a:做遞歸要寫一個方法 * b:出口條件 * c:規律 */public class DiGuiDemo { public static void main(String[] args) { int jc = 1; for (int x = 2; x <= 5; x++) { jc *= x; } System.out.PRintln("5的階乘是:" + jc); System.out.println("5的階乘是:" + jieCheng(5)); } /* * 做遞歸要寫一個方法: * 返回值類型:int * 參數列表:int n * 出口條件: * if(n == 1){return 1;} * 規律: * if(n != 1){return n*方法名(n-1);} * */ public static int jieCheng(int n){ if(n == 1){ return 1; }else{ return n*jieCheng(n-1); } }}
新聞熱點
疑難解答