我需要使用这个方法:
public static int countNegative(double[] numbers, int count){ }
计算双数组中的负数 . 如果我可以包含第3个参数sum,我可以很容易地做到这一点,但我只能使用数组和int . 我完全卡住了 . 我尝试了一些事情,但无法做到 . 我已经从数组的大小到ArrayIndexOutOfBounds,但从来没有正确的答案 . 任何人都可以帮我解决这个问题吗?
-编辑-
那么这里是确切的任务:
编写一个程序,从标准输入读取一系列数字(不是必需的整数),直到读取0,并将它们存储在一个数组中,类似于在赋值2中所做的 . 这部分是使用迭代完成的 . 您可以假设不会超过100个数字 . 然后使用递归计算存储在数组中的最大数量,负数的计数,并计算正数之和 . 因此,您将在Assignment9类中创建递归方法findMax,countNegative和computeSumPositive,并且它们将由main方法调用 . 具体来说,必须实现以下递归方法(这些方法不应包含任何循环):public static double findMax(double [] numbers,int count) - >它找到数组中的最大数,count是元素数
在数组public static int countNegative(double [] numbers,int count) - >计数负整数public static double computeSumPositive(double [] numbers,int count) - > sums of positive integer
findMax()很简单:
public static double findMax(double[] numbers, int count){
if(numbers.length - 1 == count)
return numbers[count];
else
return Math.max(numbers[count], findMax(numbers, count+1));
}
这是我最近在countNegative的尝试 . 它只返回99(我有100个元素初始化的数组):
public static int countNegative(double[] numbers, int count){
int i=0;
if(numbers[count]<0)
i=1;
if(numbers.length-1==count)
return count;
else
return i+countNegative(numbers,count+1);
}
我应该能够找出computeSumPositive,如果我能弄清楚这个负面的那个 .
伯爵可以是你需要的任何东西 . 我在findMax中更多地使用它作为索引 .
5 回答
使用
int
参数作为numbers
数组的索引 . 确定当前索引's value is negative (count 0 or 1 here). Then return the sum of that 0/1 count and the recursive call that looks at the next index position. The base case is when you' ve是否超过数组的末尾,返回0 .有什么用
count
?如果它是index
会有意义:并称之为:
你称这种方法:
countNegative(numbers, 0);
count
将用作递归的基本条件 . 您将结果返回堆栈例:
我在控制台得到
3
首先为0 elemtents的数组实现它 . 用于1个元素的数组 . 对于一个更多的数组,使用以前的结果......
这是它的工作原理
由于递归的工作方式,您不需要count参数 . 当您使用数组调用函数时,它首先确定第一个元素是否小于零,使其为负数 . 接下来,它检查数组是否有多个元素,如果是,它会使用除数组的第一个元素之外的所有元素调用自身,并将其添加到结果中 .
之后它返回结果,该结果取决于它是否在递归调用中,将其添加到其上方的调用结果或将其返回给调用它的人 .