2013-09-21 67 views
0

这是一个容易出错的问题。这个问题需要我编写一个名为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; 
} 

} 

回答

1

需要类型转换为加倍

尝试这种方式

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; 
} 

} 
+0

好吧,您的帮助表示感谢。 –

1

操作

(1/i) 

正在整数,因此将产生的结果为int的条款。将其更新为:

(1.0/i) 

得到小数结果而不是int结果。