递归求和数组中的整数 [英] recursively sum the integers in an array

查看:29
本文介绍了递归求和数组中的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我正在尝试为类编写一个程序,该程序使用递归返回数组中所有整数的总和.到目前为止,这是我的程序:

I have a program that I'm trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:

public class SumOfArray {

private int[] a;
private int n;
private int result;

    public int sumOfArray(int[] a) {

      this.a = a;
      n = a.length;

      if (n == 0)  // base case
      result = 0;
      else
          result = a[n] + sumOfArray(a[n-1]);

      return result;

   } // End SumOfArray method

} // End SumOfArray Class 

但是我收到了三个相关的错误,我相信,但我不明白为什么它会找到一种空值:

But I'm getting three error which are all related, I believe, but I can't figure out why it is finding a type of null:

SumOfArray.java:25: sumOfArray(int[]) in SumOfArray cannot be applied to (int)
    result = a[n] + sumOfArray(a[n-1]);
                    ^
SumOfArray.java:25: operator + cannot be applied to int,sumOfArray
    result = a[n] + sumOfArray(a[n-1]);
              ^
SumOfArray.java:25: incompatible types
found   : <nulltype>
required: int
    result = a[n] + sumOfArray(a[n-1]);
                  ^
3 errors

推荐答案

解决方案比看起来更简单,试试这个(假设一个非零长度的数组):

The solution is simpler than it looks, try this (assuming an array with non-zero length):

public int sumOfArray(int[] a, int n) {
    if (n == 0)
        return a[n];
    else
        return a[n] + sumOfArray(a, n-1);
}

这样称呼它:

int[] a = { 1, 2, 3, 4, 5 };
int sum = sumOfArray(a, a.length-1);

这篇关于递归求和数组中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆