以递归方式在 Java 中查找数组中数字的总和

编程入门 行业动态 更新时间:2024-10-27 08:30:03
本文介绍了以递归方式在 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 中查找数组中数字的总和

本文发布于:2023-11-30 12:22:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   总和   组中   方式   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!