Recursive dividing by 3

时间:2016-07-11 21:31:31

标签: java recursion division

Using recursion, I'm trying to divide an input by 3 all the way to the result being below 1.

So far here is what I have, but my output always turns out to be like 1 1 1 1 1 1 1 1. I believe I know where my error is on the code, but I can't think what input to use or if I coded my methods wrong. I placed a note where I believe the problem is and was wondering if anyone could support in giving a hint on how to fix this.

As well, how can I end the loop?

package divideby3;
import java.util.Scanner;

public class DivideBy3 {

    public static void main(String[] args) {
        System.out.print("Enter number >= 1:");
        int n = new Scanner(System.in).nextInt();
        System.out.println("\n Negative result is:" + n);

        for(int i = 1; i <= n; i++) {
            System.out.print(Recusion(i) + " ");
        }
    }

    public static double Recusion(double n) {
        if(n >= 1) {
            //not sure what to put here
            return ;
        }
        else {
            System.out.println("Sorry thats not number over 1!");
        }

        return Recusion(n / 3);
    }

    public static double Loop(double n) {
        if(n >= 1) {
            return 1;
        }

        double input = 0, divide = 3;
        for(double i = 0; i <= n; i++) {
            divide = (input / divide);
        }

        return divide; 
    }
}

2 个答案:

答案 0 :(得分:0)

It seems you don't understand the concept of recursion. It would be beneficial to read up on it. Simply put, Recursion is a technique where a function calls itself recursively until a condition is met.

Here is a simple example of how it works.

  public static void main(String[] args)
  {
    System.out.print(RecursiveDivision(100,3));
  }

  public static double RecursiveDivision(double dividend, int divisor) {
    if (dividend < 1)
      return dividend;

    return RecursiveDivision(dividend/divisor, divisor);
  }

答案 1 :(得分:-2)

如前所述

     public static void main(String[] args)
      {
    //you decide the number at n

System.out.print(RecursiveDivision(n,3));
}

public static double RecursiveDivision(double dividend, int divisor) {
      if (dividend < 1)
      return dividend;

return RecursiveDivision(dividend/divisor, divisor);
}