Recursive function that sums the first n recriprocals
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);
精彩评论