递归地对数组中的整数求和

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

问题描述

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

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 

但是我相信我遇到了三个相关的错误,但我无法弄清楚为什么它会找到一种 null:

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

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

上一篇:对所有元素求和 java arraylist 下一篇:字符串不能转换为int!如何在java上对扫描的int求

相关文章

最新文章