在java语言中以递归方式查找数组中所有元素的总和

0 java arrays recursion sum

这是我的代码:

public int sum(int[] array, int index) 
  {
    //int index is the number of elements in the array. 
       //Here is my base case:
    if (index == 0)
        return 0;
    //Now it's time for the recursion
    else
        return array[index] + sum(array, index + 1);
}
Run Code Online (Sandbox Code Playgroud)

我不断出错,但我不知道我做错了什么.

Roh*_*ain 8

您的基本情况有误.它应该是:

if (index == array.length)
Run Code Online (Sandbox Code Playgroud)

注意,你需要传递index = 0第一个电话.如果要传递index = array.length - 1,则保持基本情况不变,并将递归方法调用更改为pass index - 1,而不是index + 1.

但是,你真的需要递归吗?在接触递归而不是循环执行此任务之前,我会认真地给它数百个想法.