【问题标题】:Recursive Formula method implemented on another method在另一种方法上实现的递归公式方法
【发布时间】:2017-04-02 16:43:57
【问题描述】:

我有两种递归方法。其中一个有一个特殊的公式,我必须在第二种方法中使用它。我的任务是编写一个名为 reportOnValues 的递归方法,它将使用 计算方法中实现的递归公式的列表 特殊递归函数。我目前在将公式实施到我的 reportValues 方法时遇到问题。我怎么能做到这一点。

第一种方法

public static void reportOnValues(MyListOfInts m){
    if (m == null) return;
    else 
        return specialRecursiveFunction(m.firstInt) +   reportOnValues(m.restOfTheInts);
}

第二种方法

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

}

构造链表

public class MyListOfInts {

public int firstInt; // contain data
public MyListOfInts restOfTheInts; // points to next node

public MyListOfInts(int f){ // constructor 1
    firstInt=f;
}

public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
    firstInt=f;
    restOfTheInts=r;
}

}

【问题讨论】:

  • 很难告诉你你正在尝试做什么。为什么你将reportOnValues 声明为void 却试图从中返回一个值?
  • 你在实现代码时遇到了什么问题,我认为除了 lucero 提到的代码之外,给定的代码可以正常工作
  • 我猜reportOnValues 应该返回double?请澄清这一点。
  • 是的,抱歉,它是要返回一个双精度数。
  • 那么,如果您将if (m == null) return; 更改为if (m == null) return 0; 是否有效?如果不是,究竟是什么问题?

标签: java recursion linked-list


【解决方案1】:

我对您的代码做了一些更改。我认为这就是你要找的东西

    /*
     * I changed the return type to double.
     * And if (x == 1) return; To if (x == 1) return 0;
     */
    public static double specialRecursiveFunction(int x){
        if (x == 1) return 0;
        else if (x%2==1)
            return 1 + specialRecursiveFunction(x-1);
        else
            return 1 + specialRecursiveFunction(x/2);
    }

    public static double reportOnValues(MyListOfInts m){
        if (m == null) return 0;
        else 
            return specialRecursiveFunction(m.firstInt) + reportOnValues(m.restOfTheInts);
    }

MyListOfInts 类

    /*
     * I Added restOfTheInts = null; in MyListOfInts Method
     */
    public class MyListOfInts {

        public int firstInt; // contain data
        public MyListOfInts restOfTheInts; // points to next node

        public MyListOfInts(int f){ // constructor 1
            firstInt=f;
            restOfTheInts = null;
        }

        public MyListOfInts(int f, MyListOfInts r){ // constructor 2 implements nodes and data
            firstInt=f;
            restOfTheInts=r;
        }
    }

这就是我测试它的方式

public static void main(String[] args) {
        MyListOfInts list1 = new MyListOfInts(5, new MyListOfInts(13, new MyListOfInts(18, new MyListOfInts(4, new MyListOfInts(36, new MyListOfInts(5))))));
        System.out.println(reportOnValues(list1));

    }

我希望这就是你要找的东西,如果不是,我可以帮助你告诉你达到你的目标。

【讨论】:

  • 是的,这就是我要找的。​​span>
  • 如果是,您可以批准该答案为正确答案。
猜你喜欢
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 2021-06-05
  • 2014-04-25
相关资源
最近更新 更多