gpt4 book ai didi

java - 如何递归地添加随机数组的数字?

转载 作者:行者123 更新时间:2023-12-01 07:45:30 25 4
gpt4 key购买 nike

给定数组

static int[] testArray = {8, -5, 22, 17, 4, 9, -12, 15, 23, 25};'

如何递归地将所有值加在一起。我已经尝试过下面的代码,当然它不起作用。因为它应该而且不太符合逻辑,因为我不知道如何调用它

static int[] testArray = {8, -5, 22, 17, 4, 9, -12, 15, 23, 25};

static int i = 0;
public static void reverse(int sum) {
i = i+1;
int sumNum = sum;

//if ((n/10) != 0) {
sumNum = sumNum + testArray[i];
reverse(sum);
//}
}

最佳答案

static int sumRecursive(int index) {
if (index == testArray.length) {
return 0;
}
return sumRecursive(index + 1) + testArray[index];
}

我们将索引作为参数传递给函数。每次调用时,我们都会发送当前索引的值 + 1。当我们到达末尾时,我们返回 0(基本情况)。结果添加到当前元素并返回。

初始调用为 sumRecursive(0)

如果原始数组不是静态的,那么您还必须将该数组作为参数传递。

关于java - 如何递归地添加随机数组的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53834049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com