gpt4 book ai didi

java - 算术递归

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:34 25 4
gpt4 key购买 nike

我正在尝试编写一段代码,为给定的整数 n 计算以下内容:

1/1 + 1/2 + 1/3 ... + 1/n

这是我到目前为止编写的代码:

public class RecursiveSum
{
public static double Sumto(int n)
{
if (n == 0) { return 0.0; }
else if (n > 0) { return 1/n + 1/Sumto(n - 1); }
else { throw new IllegalArgumentException("Please provide positive integers"); }
}
public static void main(String[] args)
{
System.out.println(Sumto(5));
}
}

但是,它总是输出:

Infinity

问题是什么,我该如何解决?

谢谢

最佳答案

你有两个问题:

您必须执行浮点除法(即将 1/n 替换为 1.0/n),并且您应该添加 Sumto(n - 1)1.0/n 得到 Sumto(n)

  public static double Sumto(int n)
{
if (n == 0) { return 0.0; }
else if (n > 0) { return 1.0/n + Sumto(n - 1); }
else { throw new IllegalArgumentException("Please provide positive integers"); }
}

你得到 Infinity 的原因是 1/Sumto(n - 1)Sumto(n - 1) 时返回 Infinity )0.0Sumto(0)0.0

关于java - 算术递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31783702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com