有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java利用递归计算级数

我一定是没能理解在递归方法中存储值的概念。使用迭代解决这个问题需要几秒钟的时间,但我正在努力处理递归调用。基本上我是在试图解决: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);
    }

共 (1) 个答案

  1. # 1 楼答案

    您需要添加一些显式类型转换。您的1/index正在作为整数除法执行,并且您的调用正在丢失其所有精度。只需将其更改为1.0/index(或1d/index以指示1应用作double),您就可以找到所需的内容