我必须无法绕过试图在递归方法中存储值的概念.使用迭代解决这个问题需要几秒钟,但我正在努力进行递归调用.基本上我想解决: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);
}
Run Code Online (Sandbox Code Playgroud)
您需要添加一些显式类型转换.您1/index正在执行整数除法,并且您的调用正在失去其所有精度.简单地将其更改为1.0/index(或1d/index表示1应该用作a double)应该可以获得您正在寻找的内容.
| 归档时间: |
|
| 查看次数: |
540 次 |
| 最近记录: |