I'm really getting the hang of recursion (or so I think), but this problem is tripping me up. I'm trying to return 1 + 1/2 + 1/3 + ... + 1/n, but no matter what I try the method returns 1.0. I cannot for the life of me figure out what's wrong.
public static double harmonic(int n) {
if(n == 1) {
return 1;
} else {
return (1 / n) + (1 / harmonic(n - 1));
}
}
You want to use floating point division:
public static double harmonic(int n) {
if(n == 1.0) {
return 1.0;
} else {
return (1.0 / n) + (1.0 / harmonic(n - 1.0));
}
}
That is: 1/2
is 0
; 1/2.0
is 0.5
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With