java--基础3(转自传智播客,付东老师)

函数的递归

  定义:自己调用自己

 1 package test0525;
 2 
 3 public class Recursion {
 4     public static void main(String[] args){
 5 //        test();
 6 //        decimal2Binary(10);
 7 //     System.out.print(GetSum(100));
 8         System.out.print(GetSquareSum(2));
 9     }
10     
11     public static void test(){
12         System.out.print("test方法运行了");
13         test();
14     }
15     
16     //将一个十进制数,转换成二进制打印出来
17     public static void decimal2Binary(int x){
18         if(x!=0){
19             decimal2Binary(x/2);
20             System.out.print(x%2);
21             
22         }
23         
24     }
25     
26     //计算1+2+3+。。。。。。。+x的和
27     public static int GetSum(int x){
28         if(x==1){
29             return 1;
30         }
31         else{
32             return x+GetSum(x-1);
33         }
34     }
35     
36     //计算1²+2²+3²+。。。。。。n²的和
37     public static int GetSquareSum(int n){
38         if(n==1){
39             return 1;
40         }
41         else{
42             return n*n+GetSquareSum(n-1);
43         }
44     }
45     
46     
47 }
原文地址:https://www.cnblogs.com/faithfeng/p/12963739.html