以递归方式在 Java 中查找数组中数字的总和 [英] Finding the total sum of numbers in an array in Java, recursively

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

问题描述

我知道通过迭代而不是递归更容易找到数组中数字的总和,但是如果我使用递归来编写这样的函数,这段代码会有什么问题?

I understand that finding the sum of numbers in an array is much more easily done through iteration instead of recursion, but if I were to use recursion to write such a function, what would be wrong with this code?

public static double sum (double[] a) {
    if (a.length == 0)
        return 0.0;
    else{
        return sumHelper (a, 1, a[0]);
    }
}
private static double sumHelper (double[] a, int i, double result) {
    if (i < a.length) {
        result = result + sumHelper (a, i + 1, result);
    }
    return result;
}

一切运行都没有错误,但在我测试时没有返回正确的总和.

Everything runs without errors, yet does not return the correct sum when I test it out.

推荐答案

public class RecursiveSum {
    public static void main(String[] args) {
        System.out.println(sum(new double[] {1,3,4,5}));
    }

    public static double sum(double[] a) {
        if (a.length == 0)
            return 0.0;
        else{
            return sumHelper(a, 0);
        }
    }

    private static double sumHelper(double[] a, int i) {
        if(a.length - 1 == i){
            return a[i];
        }else{
            return  a[i] + sumHelper(a, i + 1);
        }
    }
}

这篇关于以递归方式在 Java 中查找数组中数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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