开发者

Recursive function that sums the first n recriprocals

开发者 https://www.devze.com 2023-03-03 23:33 出处:网络
The function below accepts an integer n and 开发者_如何学编程returns the sum of the first n reciprocals.

The function below accepts an integer n and 开发者_如何学编程returns the sum of the first n reciprocals. sum(2) should return 1.5

Here is what I have:

 public double sum(int n) {

     if (n < 0) {
       throw new IllegalArgumentException("Illegal Power Argument");
    }

    double zero = 0.0; 

    if(n == 0)
       return zero; 

    else
       return (1/n) + sum(n-1);   
 }

I am almost certain that this should work but instead it's returning 1.0 for basically everything.


You are using integer division. Cast it to a double:

return (1/(double)n) + sum(n-1);

Alternatively, use:

return (1.0/n) + sum(n-1);


(1/n) is integer division - use (1.0/n) instead.


Try this change:

return (1.0/n) + sum(n-1);   
0

精彩评论

暂无评论...
验证码 换一张
取 消