我的Java递归函数给出了错误的输出

时间:2016-03-28 02:38:51

标签: java recursion formula

我正在研究Java类。我已经正确地编写了所有方法,除了我努力学习的最后两种方法。

我的问题:我在specialRecursiveFunction中做错了什么来计算错误的输出? ...或者是我的print方法中的问题,名为reportOnValues,它打印方法specialRecursiveFunction(int x)中计算的数字

  /* Write a recursive method named reportOnValues that will use each value in 
      a list to compute a recursive formula implemented in the method 
      specialRecursiveFunction. This method cannot contain any loop.
     */

    public static void reportOnValues(MyListOfInts M){
        if( M == null) {
            System.out.println(" ");
        }
        if(M != null) {
            System.out.println(specialRecursiveFunction(M.firstInt));
            reportOnValues(M.restOfTheInts);
        }
    }


    //My Recursive Function that defines x in a function of --> f(x) = {(1--> x=0) ; (1+f(x/2) --> x=even#) ; (1+f(x-1) --> x=odd#)}

    public static double specialRecursiveFunction(int x){
        if(x == 0) {
            return 1;
        }
        else if ((x%2)==0) {
            return 1 + specialRecursiveFunction(x/2);
        }
        else {
            return 1 + specialRecursiveFunction(x-1);
        }
    }  
  

我想要的输出是......

     

3.0

     

7.0

     

4.0

     

5.0

     

5.0

我得到的输出是......

  

3.0

     

4.0

     

5.0

     

7.0

     

5.0

0 个答案:

没有答案
相关问题