计算机二级JAVA实例编程练习题2(附答案)
来源:优易学  2011-10-29 12:00:43   【优易学:中国教育考试门户网】   资料下载   IT书店
  题目:
  请用程序分别实现递和归迭代算法。
  答:
  == 递归 ==
  /**
  *
  */
  package com.test;
  /**
  *
  */
  public class CallSelf {
  /**
  * @param args
  */
   public static void main(String[] args) {
  // int
  int number=4;
  // call sum
  System.out.println("sum("+number+")="+sum(number));
  // call getFactorial
  System.out.println("getFactorial("+number+")="+getFactorial(number));
  }
  /**
  * sum up an number to 1
  * @param x
  * @return
  */
  public static int sum(int x){
  //break
  if(x<=0){
  return x;
  }
  //call self & sum up
  int total=x+sum(x-1);
  return total;
  }
  public static int getFactorial(int x){
  //condition
  if(x==1){
  return 1;
  }
  //call self & get factorical
  return x*getFactorial(x-1);
  }
  }
  == 迭代 ==
  /*
  * 斐波那契方法 采用迭代方法解决
  * @param n 要求的那项位置
  * @return 结果
  */
  public static int feibo(int n)
  {
  int start1 = 1;
  int start2 = 1;
  for(int i = 2; i < n; i++)
  {
  int temp = start1+start2;
  start1 = start2;
  start2 = temp;
  }
  return start2;
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训