这是一个简单的问题,但我遇到了麻烦。这个问题需要我编写一个名为fractionSum 的方法,它接受一个整数参数并返回前n 项之和的 double 值。
例如,如果参数为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;
}
}
最佳答案
您需要输入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;
}
}
关于java - 累计金额问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18929647/