0

数値を取る配列があります。私の方法の 1 つは、配列内の正の数の数を数えることです。したがって、2 3 4 5 6 と 0 を入力してプログラムを終了するとします。正の数値: 5 を出力する必要がありますが、代わりに正の数値: 4 を出力します。最後の数値を見逃しています。ただし、2 3 4 5 -1 4 0 {0 終了} を実行すると、この場合は 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);     
    }
}
4

2 に答える 2

0

コードが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);
于 2013-11-11T14:40:55.563 に答える
0

すべてのコードを貼り付けるために、最初にコード全体を貼り付けます。

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);
    }
}

このコードは、30、40、55、62 の 4 4 の正の数を返しました。
配列と 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 です。もう一度試してみてください。

于 2013-11-08T21:37:10.747 に答える