2015-02-09 65 views
-1

仍在学习,我似乎无法总结我的脑袋上似乎像一件容易的事。 的computeMethods方法的就是IM完全以难倒,但是相反的方法,我只是不断取回相同的整数而不会被逆转。编程作业递归

/**************************** 
     * For Method Computemethods1 i must compute series 
     * b(x)=1/3+2/5+3/7..... +x/2x+1 
     * For method ComputeMethod2 
     * 1/2+2/3+......... x/(x+1) 
     *******************************/ 
     public static int computeMethod1(int x){ 
     if (x==0) 
      return 0; 
     if (x==1) 
      return 1; 
     return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2)); 
     } 


     public static int computeMethod2(int x){ 
     if (x==0) 
      return 0; 
     return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1); 
     } 
     /******************** 
     * For method reverseMethod i must reverse a user given int 
     **********************/ 
     public static int reverseMethod(int x){ 
     int reversedNum=0; 
     if (x!=0) 
      return x; 
     reversedNum=reversedNum *10 +x%10; 
     return reversedNum+reverseMethod(x/10); 


     } 
     /****************** 
     * For method sumDigits i must use recursion 
     * to sum up each individual number within the int 
     ********************/ 

     public static long sumDigits(long n){ 
     if(n==0) 
      return 0; 
     if (n==1) 
      return 1; 
     else 
      return n+sumDigits(n-1); 
     } 
    } 
+0

'X-1/3'可能与整数除法的问题?尝试使用'float'或'double'数字,即'x-1。/ 3.'并相应地更改方法的参数。另外,sumDigits似乎有点偏离...实际上,它更像是“从1到n的所有数字的总和”。 – 2015-02-09 09:29:47

+0

你的问题是什么?您应该指定什么不按预期工作。另外,请删除不相关的代码。 – 2015-02-09 09:30:39

回答

2

对于反向方法,使用的是:if (x!=0) return x;

可能是你需要使用方法:if (x==0) return x。所以逻辑是,如果给定的参数是0,则返回0,否则返回倒数。

P.S:正如有人在comentaries提到的,请照顾的类型,所以为师,你可以更好地使用floatdouble,并照顾业务优先级为正确的结果,所以(x+1)/2将从x+1/2不同。

0

对于您的每一个方法,跟进您的小x代码。

例如,computeMethod1应该返回:

  • 1/3x == 1,而目前它只是简单地返回1(注意,返回类型将需要比int以外的东西。)。

  • 1/3 + 2/5x == 2

  • 1/3 + 2/5 + 3/7x == 3

对于每个x,注意我们如何使用以前的结果,即computeMethod1(x - 1)

当你遇到的代码看起来并没有达到你期望的程度时,让你的代码更简单更简单,直到你能够缩小问题的位置,然后希望问题会变得明显,或者在线文档可以告诉你。