编程作业 - 递归


仍在

学习,我似乎无法理解这似乎是一件容易的事。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);
      }
    }

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

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

PS:正如有人在 comentaries 中提到的,请注意类型,因此对于除法,您最好使用 floatdouble,并注意操作优先级以获得正确的结果,因此(x+1)/2将与x+1/2不同。

对于每个方法,请遵循小 x 的代码。

例如,computeMethod1应返回:

  • 1/3 对于 x == 1 ,而目前它只是返回 1 (注意,返回类型需要不是 int (。

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

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

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

当你遇到似乎没有达到预期效果的代码时,让你的代码越来越简单,直到你可以缩小问题所在,然后希望问题是什么很明显,或者在线文档可以告诉你。

最新更新