faithfeng

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

2020-05-26 10:51  晓峰如月  阅读(120)  评论(0编辑  收藏  举报

函数的递归

  定义:自己调用自己

 

 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 }

 

分类:

技术点:

相关文章:

  • 2022-02-10
  • 2022-12-23
  • 2021-11-22
  • 2021-06-06
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
  • 2021-11-22
  • 2021-08-16
  • 2021-11-24
  • 2022-12-23
相关资源
相似解决方案