【问题标题】:Issue with Cumulative Sum累计金额问题
【发布时间】:2013-09-21 06:26:38
【问题描述】:

这是一个我遇到麻烦的简单问题。这个问题需要我编写一个名为 fractionSum 的方法,它接受一个整数参数并返回前 n 项之和的双倍。

例如,如果参数为 5,则程序会将 (1+(1/2)+(1/3)+(1/4)+(1/5)) 的所有分数相加。换句话说,它是黎曼和的一种形式。

由于某种原因,for 循环没有累加总和。

代码如下:

public class Exercise01 {

public static final int UPPER_LIMIT = 5;

public static void main(String[] args) {
    System.out.print(fractionSum(UPPER_LIMIT));
}

public static double fractionSum(int n) {

    if (n<1) {
        throw new IllegalArgumentException("Out of range.");
    }

    double total = 1;

    for (int i = 2; i <= n; i++) {
        total += (1/i);
    }

    return total;
}

}

【问题讨论】:

    标签: java for-loop cumulative-sum


    【解决方案1】:

    你需要键入 cast to double

    试试这个方法

    public class Exercise01 {
    
    public static final int UPPER_LIMIT = 5;
    
    public static void main(String[] args) {
        System.out.print(fractionSum(UPPER_LIMIT));
    }
    
    public static double fractionSum(int n) {
    
        if (n<1) {
            throw new IllegalArgumentException("Out of range.");
        }
    
        double total = 1;
    
        for (int i = 2; i <= n; i++) {
            total += (1/(double)i);
        }
    
        return total;
    }
    
    }
    

    【讨论】:

      【解决方案2】:

      操作

      (1/i)
      

      正在处理整数,因此将生成 int 形式的结果。将其更新为:

      (1.0/i)
      

      获取小数结果而不是 int 结果。

      【讨论】:

        猜你喜欢
        • 2017-08-01
        • 2016-03-27
        • 2017-09-28
        • 1970-01-01
        • 2022-10-25
        • 2023-03-15
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多