JAVA递归和迭代方法

时间:2013-03-21 18:07:12

标签: java recursion iteration

您好我对我的代码有一个简单的问题,我需要知道错误的位置以及为什么它没有正确显示递归和迭代方法(这会返回stackoverflow错误)。感谢

import java.util.Scanner;

public class Progression {
    public static int geometricRecursive(int x){
        if(x  == 1)
            return 1;
        else {
            return x * geometricRecursive(x - 1);
        } 
    }

    public static int harmonicRecursive(int x){
        if(x == 1)
            return 1;
        else {
            return x * harmonicRecursive(1/(x - 1));
        }
    }

    public static int geometricIterative(int num){
        int result = 0;
        if(result == 1)
            return result;
        else
            for(int i = 2; i < num; i++){
                result = (i * (i + 1));
            }
        return result;
    }

    public static int harmonicIterative(int num){
        int result = 0;
        if (result == 1)
            return result;
        else
            for (int i = 2; i < num; i ++){
                result = (i * (1/(i+1)));
            }
        return result;
    }

    public static void main(String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        System.out.println("This program will calculate the geometric and ");
        System.out.println("harmonic progression for the number you enter.");
        System.out.print("Enter an integer that is greater than or equal to 1: ");
        int input = keyboard.nextInt();
        int geomAnswer = geometricRecursive (input);
        double harmAnswer = harmonicRecursive (input);
        System.out.println("Using recursion:");
        System.out.println("The geometric progression of " + input + " is " + geomAnswer);
        System.out.println("The harmonic progression of " + input + " is " + harmAnswer);
        geomAnswer = geometricIterative (input);
        harmAnswer = harmonicIterative (input);
        System.out.println("Using iteration:");
        System.out.println("The geometric progression of " + input + " is " + geomAnswer);
        System.out.println("The harmonic progression of " + input + " is " + harmAnswer);
    }
}

3 个答案:

答案 0 :(得分:3)

您获得了StackOverflow,因为您没有正确执行分区。你正在进行整数除法,这会产生错误的结果。这导致在递归算法中没有达到基本条件。

要解决此问题,请使用双打并更改基本条件:

public static double harmonicRecursive(double x)
{
   if(x <= 1.0)
   {
       return 1.0;
   }
   else
   {
       return x * harmonicRecursive(1.0 / (x - 1.0));
   }
}

答案 1 :(得分:2)

return x * harmonicRecursive(1/(x - 1));方法中的违规行为harmonicRecursive(int x)。代码的1/(x - 1)部分将为所有0返回x > 2。如果您在该函数中输入大于2的任何内容,则if语句仅检查x == 1这是一个问题。

答案 2 :(得分:1)

以这种方式更改此方法:

public static int harmonicRecursive(int x){

   if(x <= 1) //Here

       return 1;

   else {

      return x * harmonicRecursive(1/(x - 1));

   }
}