[英]Tail Recursion - Java
I am trying to create a method that is tail recursive and finds the sum
of an equation ( i / 2i + 1
) where i
needs to increment 1-10
. 我正在尝试创建一种尾部递归的方法,并找到等式的
sum
( i / 2i + 1
),其中i
需要增加1-10
。 I'm having trouble with how to reach the base case and make the recursion cease. 我在达到基本情况并使递归停止方面遇到麻烦。
This is what I have so far: 这是我到目前为止的内容:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries());
}
public static double sumSeries(){
int i = 10;
if (i == 0)
return 0;
else
return (i / (2 * i + 1));
}
}
I think that you are looking something like that: 我认为您正在寻找类似的内容:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries(10,0));
}
public static double sumSeries(int i,double result){
if (i == 1)
return result;
else{
double res = result + (i / (double)(2 * i + 1));
return sumSeries(i-1,res);
}
}
}
If you want recursion, your method should look something like this: 如果要递归,则方法应如下所示:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries());
}
// if you want to keep the argument-less method in main but want to calculate
// the sum from 1 - 10 nevertheless.
public static double sumSeries() {
return sumSeries(10);
}
public static double sumSeries(int i){
if (i == 0) {
return 0;
}
else {
// The cast to double is necessary.
// Else you will do an int-division here and get 0.0 as result.
// Note the invocation of sumSeries here inside sumSeries.
return ((double)i / (2 * i + 1)) + sumSeries(i-1);
}
}
}
If you're looking for a way to find this sum : 如果您正在寻找一种求和的方法:
(1 / 2*1 + 1) + (2 / 2*2 + 1) + (3 / 2*3 + 1) + ... + i/(2i + 1)
You could try this : 您可以尝试这样:
public double sumSeries(int i) {
if (i == 1) { // base case is 1 not 0
return 1/3;
} else {
double s = i / (2.0 * i + 1.0);
return s + sumSeries(i - 1);
}
}
Your method is not recursive. 您的方法不是递归的。 A recursive method needs to use 'himself' and at a certain condition it stops.
递归方法需要使用“他自己”,并且在特定条件下它将停止。 An example:
一个例子:
public static double sumSeries(int x) {
if (x == 0)
return x;
else {
return x + sumSeries(x - 1);
}
for your example, something like this would fit: 对于您的示例,类似以下内容将适合:
public static double sumSeries(double x) {
if (x == 0)
return x;
else
return (x / (2 * x + 1)) + sumSeries(x - 1.0);
}
If I understood your algorithm correctly :) If not, edit the algorithm :) 如果我正确理解了您的算法:)如果不正确,请编辑算法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.