递归麻烦

时间:2013-12-04 05:12:53

标签: java recursion

我的高中有一个Java课程,作为练习题之一,我们必须追踪这个递归程序:

public class Loop {

    public static void main(String[] args) {
        double x = okay(6, 1.5);
        System.out.println("x is" + x);
    }

    public static double okay(int w, double z) {
        System.out.println(w + "," + z);
        if (z > -15) {
            return okay(w += 3, z - w) - z;
        } else
            return 12;
    }
}

除最后一行外,我已正确追踪此程序。我的老师说我的最终答案(我写的12.0)是不正确的,正确答案是16.0。如果你们其中一个人能解释这对我有用,我将非常感激。提前谢谢。

4 个答案:

答案 0 :(得分:3)

追踪递归调用:

  1. x = okay(6, 1.5)
  2. System.out.println(6 + "," + 1.5) => “6,1.5”
  3. return okay(6, (1.5 - 9)) - 1.5
  4. System.out.println(6 + "," + -7.5) => “6,-7,5”
  5. return okay(6, (-7.5 - 9)) - -7.5
  6. System.out.println(6 + "," + -16.5) => “6,-16.5”
  7. return 12
  8. 然后,回到链上:

    1. return 12
    2. return 12 - -7.5 => 19.5
    3. return 19.5 - 1.5 => 18.0
    4. x = 18.0
    5. System.out.println("x is" + 18.0); => “x是18.0”

答案 1 :(得分:1)

你错了......答案是18.0 .....

解决此问题的最佳方法是将代码复制/粘贴到您喜欢的IDE中,然后运行它....

就我而言,它给出了输出:

6,1.5
9,-7.5
12,-19.5
x is18.0

而且,我认为Java在这种情况下是正确的。

答案 2 :(得分:1)

您可以将其视为:

okay(6,1.5)
   okay(9,-7.5) - 1.5
       okay(12,-16.5) - (-7.5)
       return 12 + 7.5
   return 19.5 - 1.5
18.0

要了解更好地查看此问题: Java recursion Understanding

答案 3 :(得分:0)

我同意以前的答案。一种让人们更容易看到正在发生的事情的方法是为返回值添加打印输出:

  public static double okay(int w, double z) {
    System.out.println(w + "," + z);
    if (z > -15) {
      double result = okay(w += 3, z - w) - z;
      System.out.println("Returning "+result);
      return result;
    } else
      System.out.println("Returning 12");
      return 12;
  }

输出结果为:

6,1.5
9,-7.5
12,-19.5
Returning 12
Returning 19.5
Returning 18.0
x is18.0