我正在尝试创建一种尾部递归的方法,并找到等式(sum)的i / 2i + 1,其中i需要递增1-10。我在达到基本情况并使递归停止方面遇到麻烦。

这是我到目前为止所拥有的:

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));
    }
}

最佳答案

如果要递归,则方法应如下所示:

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);
        }
    }
}

09-29 19:34