【发布时间】:2013-11-21 00:32:57
【问题描述】:
我有一个接受数字的数组。我的一种方法是计算数组中正数的数量。因此,如果他们输入 2 3 4 5 6 和 0 来终止程序。它应该输入打印出正数:5,但它打印出正数:4。它错过了最后一个数字。但是,如果我执行 2 3 4 5 -1 4 0 {0 terminate},它会在这种情况下打印出正确的正数数 5。我已经进行了一些调试,但似乎无法弄清楚。有什么帮助吗?
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);
}
}
【问题讨论】:
-
你的缩进到处都是,你应该更正它,这样你的代码更容易阅读。 Eclipse 可以为您做到这一点。
-
它对我来说很好用。如果我使用
countPositive(new int[] { 2, 3, 4, 5, 6}, 0, 4)结果是5。 -
您使用的索引开始和结束是什么?
-
他可能使用 indexStart 作为 1 应该是 0
-
不,我从 0 开始