码迷,mamicode.com
首页 > 其他好文 > 详细

1加到100

时间:2018-06-07 19:34:59      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:height   测试   public   style   size   ||   ret   bsp   使用   

1、使用循环实现

public static int add (int num) {

  int result = 0;

  for( int  i = 1; i <=num ; i++) {

    result  += i;

  }

  return result;

}

2、用递归实现

/*
* 令f(100)=1+2+3+..+100;
* f(99)=1+2+3+..+99;
*
* f(n)=f(n-1)+n
*
* */

public static int fac ( int num) {

  if(num == 1 || num == 0){

    return 1;  

  }else{

    return fac(num -1) + num;

  }

}

在主方法里面调用就可以了,或者用junit的test测试

1加到100

标签:height   测试   public   style   size   ||   ret   bsp   使用   

原文地址:https://www.cnblogs.com/Eileen-lu/p/9151818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!