简体   繁体   中英

Recursion Trouble

I have a Java class in my High School, and as one of the practice problems, we had to trace this recursive program:

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;
    }
}

I had traced this program correctly except for the last line. My teacher had said that my final answer(I wrote 12.0) was incorrect, and that the correct answer was 16.0. I would highly appreciate if one of you guys would explain how this works for me. Thanks in advance.

Tracing down the recursive calls:

  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

Then, going back up the chain:

  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 is 18.0"

You are all wrong ... the answer is 18.0 .....

The best way to solve this problem is copy/paste the code in to your favourite IDE, and to run it....

In my case, it gives the output:

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

And, I presume Java is right in this case.

You can view it like :

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

To understand better view this question too : Java recursion Understanding

I agree with the previous answers. One way to make it easier to see what is going on is to add a printout for the return values:

  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;
  }

The output is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM