2015-08-21 30 views
-1

我的任務是:創建一個方法來搜索一個值的無序整數數組, 如果找到該值,返回它在數組中的位置的索引,如果未找到,則返回-1。無序數組線性搜索C++

它只是找到我輸入的數字,如果它在索引0,否則它說它找不到。我不確定出了什麼問題,當我初始化自己的數組時,它正在工作,但現在不會,因爲我有用戶創建自己的數組。

任何幫助將是偉大的!謝謝!

到目前爲止,我的代碼是:

#include <iostream> 

using namespace std; 


//SearchArray prototype 
int SearchArray(int arInt[], int elementAmount, int intSearched); 


int main() 

{ 
    int arInt[50]; 
    int elementAmount; 
    int intSearched = 0; 
    int i; 

    cout << "How many elements would you like to add to your array?\n"; 
    cin >> elementAmount; 

    for(i = 0; i < elementAmount; i++) 
    { 
     cout << "Enter Number: "; 
     cin >> arInt[i]; 
    } 

     cout << "Search array for integer:\n"; 
     cin >> intSearched; 

     //Call search array method 
     SearchArray(arInt, elementAmount, intSearched); 


    system("pause"); 
    return 0; 
} 


int SearchArray(int arInt[], int elementAmount, int intSearched) 
{ 
     int i; 
     bool foundInt = false; 

     for (i=0; i < elementAmount; i++) 
     { 
      if(arInt[i] == intSearched) 
      { 
       foundInt = true; 
       cout << "Integer was found in array at index " << i << endl; 
      } 
      else if (!foundInt) 
      { 
       cout << "Integer was not found in array\n"; 

       system("pause"); 
       return -1; 
      } 


     } 

} 
+0

爲什麼'SearchArray'方法中沒有任何代碼? – unrealsoul007

+0

當你在調試器下運行時會發生什麼? –

+1

除了其他所有內容外,此代碼還存在非常危險的錯誤 - SearchArray在數組中找到元素時不會返回值。 – SergeyA

回答

0

下面的代碼添加到您的代碼SearchArray方法,它工作正常

int SearchArray(int arInt[], int elementAmount, int intSearched) 
{ 
    for(int i=0; i< elementAmount; i++) 
    { 
     if (arInt[i] == intSearched) 
      return i; 
    } 
    // element not found! 
    return -1; 
} 

,並添加以下爲您main結束檢索答案

int ans = SearchArray(arInt, elementAmount, intSearched); 
cout<<"Indexed of the element"<<ans<<endl; 
+0

謝謝!它現在工作:) – groot

0

那是因爲你總是結束你的第一個元素的搜索。假設數組是

arr=[3,5,7] and intSearched is 5. 

現在,在您SearchArray()功能foundInt最初設置爲false。因此,當i = 0 and arInt[i] == intSearched條件不成立時,由於foundIntfalse,因此發送到else聲明。並從那裏返回-1。像下面的東西會更簡單,做這個工作:

int SearchArray(int *arInt, int elementAmount, int intSearched) 
{ 
    int i; 
    for(i=0; i < elementAmount; i++) 
    { 
     if(arInt[i] == intSearched) 
     { 
      cout << "Integer was found in array at index " << i << endl; 
      return 1; 
     } 
    } 
    cout << "Integer was not found in array\n"; 
    system("pause"); 
    return 0; 
}