2011-12-05 165 views
1

我一定是没有围绕试图在递归方法中存储一个值的概念。使用迭代解决这个问题需要几秒钟,但我正在为递归调用而挣扎。基本上我试图解决:1/1 + 1/2 + 1/3 ...使用递归来计算一系列

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in);  

    System.out.print("Enter in the end number for the sequence: "); 
    int endpoint = input.nextInt(); 

    System.out.println("The value of the sequence is : " + calcSequence(endpoint)); 

    } 

    public static double calcSequence (int index){ 

     if (index == 0) 
      return 0; 
     else 
      return (1/index) + calcSequence(index - 1); 
    } 

回答

6

您需要添加一些明确的类型转换。您的1/index正在执行整数除法,并且您的通话正在失去其所有精度。只需将其更改为1.0/index(或1d/index以指示应使用1作为double)即可获得您要查找的内容。

+1

我知道这是愚蠢的。我爆发了笔和纸,似乎在逻辑上合理。 – MISMajorDeveloperAnyways