0

我想得到一个数组中偶数的总和:

 public static void main(String[] args) {
    int[] array = new int[4];
    array[0] = 1;
    array[1] = 2;
    array[2] = 2;
    array[3] = 4;

    System.out.println("Count even: " + countE(array, 0));      
 }   

public static int countE(int[] arr, int head) {
        if (arr.length == head) {
        return -1;
        } else if (arr[head] % 2 == 0) {              

            return 1 + countE(arr, head + 1);
    } else {

        return 0 + countE(arr, head + 1);
    }
}
4

6 回答 6

0
if (arr.length == head) {
        return -1;

给你问题兄弟......你从最终计数中减去1......尝试做

if (arr.length == head) {
        return 0;
于 2013-10-08T05:31:01.470 回答
0

它可以通过递归来完成,你添加的数字是错误的

        else if (arr[head]%2==0)
        {
            return arr[head] +  countHead(arr, head + 1);
        }
于 2013-10-08T05:31:11.690 回答
0

它给你 2 因为在最后一次递归中,它减去 1——你的基本情况是错误的。改为返回 0。

于 2013-10-08T05:31:41.953 回答
0

我希望我没有为你透露太多,它会带走学习的兴奋!

public static int countE(int[] array, int index) {
  int currentNumber = array[index];
  if(index == array.length) {
    // terminate it by returning a value that does not affect the sum (what integer is this?)
  } else {
    // check if even, if even, add the current number, else, add zero (both are recursive calls)
    if(isEven(currentNumber)) {
       return // your recursive call if even, currentNumber should be added
    } else {
       return // your recursive call if not, currentNumber should not be added
    }
  }
}

public static boolean isEven(int number) {
  return (number % 2 == 0) ? true : false;
}
于 2013-10-08T05:53:45.600 回答
0

喂。伙计..试试这个

package com.smk.recursion;

public class SumOfEvenNoFromArray {
public static void main(String[] args) {

    int[] a = new int[5];
    a[0] = 2;
    a[1] = 5;
    a[2] = 4;
    a[3] = 4;
    a[4] = 4;

    System.out.println("Sum of Odd Numbers : "+sumEvenNoRecursion(a,(a.length-1)));

}

public static int sumEvenNoRecursion(int[] arr, int index){
    int sum;
    if(index == -1){
        return 0;
    }else if(arr[index]%2 == 0 ){           
        sum = arr[index] + sumEvenNoRecursion(arr, --index);            
    }else{
        sum =  sumEvenNoRecursion(arr, --index);            
    }
    return sum;


}
}

//输出

奇数和:14

于 2013-10-08T06:09:39.530 回答
0

您可以使用辅助函数进行递归。

public static int sumofEvens(int[] list){
    int sum = sumHelper(list, 0, 0);
    return sum;
}
private static int sumHelper(int[] list, int i, int sum){
    if(i < list.length){
        if(list[i] % 2 == 0){
            sum += list[i];
        }
        sum = sumHelper(list, i+1, sum);
    }
    return sum;
}
于 2017-06-22T14:48:55.213 回答