我的java递归函数输出错误

2q5ifsrm  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(180)

我正在开发一个java类。我已经正确地写了所有的方法,除了最后两个我正在努力的方法。
我的问题是:我在计算错误输出的特殊执行函数中做错了什么。。。或者是我的打印方法reportonvalues中的问题,它打印在方法specialrecursivefunction(intx)中计算的数字

/* 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
7
4
5
5
我得到的结果是。。。
3
4
5
7
5

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题