递归阵列添加正数 [英] Recursion array adding positive numbers
问题描述
我有一个数组,它需要的数字。我的一个方法是计算在阵列中的正数的数量。因此,如果他们进入2 3 4 5 6和0以终止程序。它应该输入打印出模型正数:5,而是它打印出正数:4,它忽略了最后一个号码。但是,如果我做的2 3 4 5 -1 4 0 {0}终止它打印出正数的正确的数字在这种情况下5.我已经做了一些调试,但不能似乎弄明白。任何帮助吗?
公共静态INT countPositive(INT []号,诠释了startIndex,诠释endIndex的)
{
如果(==了startIndex endIndex的)
{
如果(数字[了startIndex]&0)
{
返回1;
}
其他
返回0;
}
其他
{
如果(数字[了startIndex]&0)
{
返回1 + countPositive(数字,则startIndex +1,endIndex的);
}
其他
返回countPositive(数字,则startIndex +1,endIndex的);
}
}
这是可怕的,即code有2个不同的else分支相同的逻辑。更好:
如果(的startIndex> endIndex的)返回0;
其他
返回
(数字[了startIndex]大于0?1:0)
+ countPositives(数字,则startIndex + 1,endIndex的);
此外,为整个数组数做的:
countPositives(数字0,length.numbers-1);
I have an array that takes numbers. One of my methods is to count the number of positive numbers in the array. So if they enter 2 3 4 5 6 and a 0 to terminate the program. It should input print out Postive numbers: 5 but instead it prints out Positive Numbers : 4. Its misses the last number. However, if i do 2 3 4 5 -1 4 0 {0 terminates} it prints out the correct numbers of positive numbers in this case 5. I've done some debugging but cant seem to figure it out. Any help?
public static int countPositive(int[] numbers, int startIndex, int endIndex)
{
if (startIndex == endIndex)
{
if (numbers[startIndex] > 0)
{
return 1;
}
else
return 0;
}
else
{
if (numbers[startIndex] > 0)
{
return 1 + countPositive(numbers, startIndex +1, endIndex);
}
else
return countPositive(numbers, startIndex +1, endIndex);
}
}
It is terrible, that the code has the same logic in 2 different else branches. Better:
if (startIndex > endIndex) return 0;
else
return
(numbers[startIndex] > 0 ? 1 : 0)
+ countPositives(numbers, startIndex+1, endIndex);
Also, to count the whole array do:
countPositives(numbers, 0, length.numbers-1);
这篇关于递归阵列添加正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!