问题描述
我确实掌握了递归的技巧(或者,我认为),但是这个问题使我不寒而栗.我正在尝试返回1 + 1/2 + 1/3 + ... + 1/n,但是无论我尝试什么,该方法都将返回1.0.我一辈子都无法找出问题所在.
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));
}
}
推荐答案
好吧,对于一个,您不想返回(1/n)+(1/谐波(n-1))
,但还需要使用 double
算术:
Well, for one, you don't want to return (1 / n) + (1 / harmonic(n - 1))
, but also you need to use double
arithmetic:
public static double harmonic(int n) {
if(n == 1) {
return 1.0;
} else {
return (1.0 / n) + harmonic(n - 1);
}
}
如果将其保留为 1/谐波
,则会完全返回另一个函数:
If you left it as 1 / harmonic
you'd return another function entirely:
这是一个非常令人困惑的功能,顺便说一句,但是我认为(我第三次编辑它)这次我做对了.
That is a very confusing function to figure out, btw, but I think (with my 3rd time editing it) I got it right this time.
这篇关于谐波序列递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!