簡體   English   中英

遞歸方法的問題

[英]Trouble with a recursive method

public static boolean array6(int[] nums, int index) {
    if(nums.length > index+1) 
    {
        if(nums[index] == 6)
            return true;
        else
            array6(nums,index+1);
    }
    else if(nums.length==index+1)
    {
        if(nums[index] == 6)
            return true;
        else
            return false;
    }
    return false;
}

作為我的 CSA 類練習的一部分,我們必須編寫一個方法來查找 int 數組中是否存在 6 並返回相應的布爾值。 如果數組中的第一個數字是 6,則我編寫的方法有效,否則就無效。 為什么?

注意:必須遞歸完成

問題是您沒有觸發遞歸,因為您的代碼中沒有任何地方返回方法本身的結果。 如果條件為true ,則重寫if statement的內容,如下所示,將使其按預期工作:

if (nums.length > index_next) 
{
    if (nums[index] == 6)
        return true;

    // you have to return the result of the function here
    // in order to obtain an effective recursion, otherwise the
    // method is called but it's output value is ignored and the
    // functions goes outside the scope of the if statement
    // reaching the "return false" located at the bottom
    return array6(nums, index_next);
}

但總的來說,你的函數包含很多問題。 您的任務非常簡單,但您正在以極其復雜的方式對其進行編碼。 您可以使用許多內置函數來實現相同的結果……即使您不想使用它們,一個簡單的for loop也可以完成這項工作:

boolean found = false;

for (int i = 0; i < nums.length; ++i)
{
    if (nums[i] == 6)
    {
        found = true;
        break;
    }
}

編輯:遞歸實現

public static boolean array6(int[] nums, int index)
{
    if (index == nums.length)
        return false;

    if (nums[index] == 6)
        return true;

    return array6(nums, index + 1);
}

緊湊的解決方案

bool array6(int* array, int len, int index) {

    if (index == len) {
        return false;
    }

    return array[index] == 6 || array6(array, len, index + 1);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM