簡體   English   中英

函數在應該返回值時不返回值

[英]Function does not return value when it should

我寫了以下代碼進行二分查找

int binarySearch(int input[], int start, int end, int element) {
    
    if(start<=end) { 
        
        int mid = (start+end)/2;

        if(input[mid]==element) {
            cout<<"mid will be returned\n";
            return mid;       
        }

        else if(input[mid]<element) {
            binarySearch(input, mid+1, end, element);
        } else if (input[mid]>element) {
            binarySearch(input, start, mid-1, element);
        }
    }
    return -1;
}

現在,對於輸入

10                    //size of array
1 2 3 4 5 6 7 8 9 10  //array
1                     //element to be found

我得到輸出

mid will be returned
-1

但是如果我在return -1之前放一個 else(在倒數第二行),它就可以正常工作並返回

mid will be returned
0

問題是,函數不應該在第一種情況下只返回mid = 0return 0嗎?

以下是主要功能供您參考:


int main() {
    int input[100000],length,element, ans;
    cin >> length;
    for(int i =0;i<length;i++)
    { 
        cin >> input[i];;
    }

    cin>>element;
    ans = binarySearch(input, 0, length-1,  element);
    cout<< ans << endl;
}

您必須在遞歸調用之前return

int binarySearch(int input[], int start, int end, int element) {
    
    if(start<=end) { 
        
        int mid = (start+end)/2;

        if(input[mid]==element) {
            cout<<"mid will be returned\n";
            return mid;       
        }

        else if(input[mid]<element) {
            return binarySearch(input, mid+1, end, element); // here
        } else if (input[mid]>element) {
            return binarySearch(input, start, mid-1, element); // here 
        }
    }
    return -1;
}

在您再次調用該函數的位置添加 return。 Return 會將值返回給調用者函數,因此每個遞歸都會將值返回給其調用者函數。 所以你的代碼應該是,

int binarySearch(int input[], int start, int end, int element) {
    
    if(start<=end) { 
        
        int mid = (start+end)/2;

        if(input[mid]==element) {
            cout<<"mid will be returned\n";
            return mid;       
        }

        else if(input[mid]<element) {
            return binarySearch(input, mid+1, end, element);
        } else if (input[mid]>element) {
            return binarySearch(input, start, mid-1, element);
        }
    }
    return -1;
}

您的代碼似乎是正確的,除了您沒有在遞歸函數中返回binarySearch的結果。

這樣就被執行了,但結果並沒有被原始(頂級) binarySearch調用使用。

為了讓主程序得到binarySearch方法的正確值,它應該每次都調用自己。

更改此部分並重試:

else if(input[mid]<element) {
            return binarySearch(input, mid+1, end, element);
        } else if (input[mid]>element) {
            return binarySearch(input, start, mid-1, element);
        }

暫無
暫無

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

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