【问题标题】:Recursion array adding positive numbers递归数组添加正数
【发布时间】: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 开始

标签: java arrays recursion


【解决方案1】:

太糟糕了,代码在 2 个不同的 else 分支中具有相同的逻辑。更好:

if (startIndex > endIndex) return 0;
else 
    return
       (numbers[startIndex] > 0 ? 1 : 0) 
       + countPositives(numbers, startIndex+1, endIndex);

另外,要计算整个数组:

countPositives(numbers, 0, length.numbers-1);

【讨论】:

    【解决方案2】:

    要粘贴所有代码,首先是整个代码:

    public class JavaApplication5 {
    
        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);     
        }
    }
        public static void main(String[] args) {
    
            int i=countPositive(new int[] { -3, 30, 40, 55, 62}, 0, 4);
            System.out.println(i);
        }
    }
    

    这段代码返回了 4 4 个正数:30,40,55,62。
    您可以使用数组和 strt 以及结束索引。

    int i=countPositive(new int[] { -3, 30, 40, 55, 62,-3, 43}, 0, 6);
    

    上面的代码返回了 5——正数的个数。

    int i=countPositive(new int[] { -3, 30, 40, 55, 62,-3, 43}, 3, 6);
    

    返回给我 3 个正数:从 55,62,-3 和 43 分别是 55,62 和 43。 再试一次。

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多