加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 算术递归

发布时间:2020-12-14 17:41:10 所属栏目:Java 来源:网络整理
导读:我正在尝试编写一个代码,为给定的整数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
我正在尝试编写一个代码,为给定的整数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.0 / n替换1 / 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的原因是当Sumto(n – 1)为0.0,Sumto(0)为0.0时,1 / Sumto(n – 1)返回Infinity.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读