2013-09-28 172 views
0

你好傢伙我在這裏尋求幫助來完成我的計劃。那麼下面的代碼運行,但它不執行它應該做的所有任務。程序應該要求用戶輸入5個數字以存儲在數組中。其次,它應該詢問用戶他想要找到的陣列內的數字。之後,如果在數組中找到數字,它應該顯示它的位置(索引/索引),如果沒有,它應該顯示該數字不在數組內。連續搜索查詢

我的問題是即使要搜索的數字不在數組內,它仍然會顯示一個索引。另一個問題是,當我在數組中輸入常用數字時,例如我想搜索3:{3,3,54,0,8},它只顯示「第一個」數字3的索引,並且不顯示「第二」三號的指數。請幫助我謝謝。

#include<iostream> 
#include<conio.h> 

using namespace std; 

int main() 
{ 
    int list[5], a, loc = 0, searchItem, listLength; 
    bool found = false; 

    cout<<"Enter 5 numbers: "<<endl; 
    for(a = 0; a < 5; a++) 
       cin >> list[a]; 

    cout<<"\n\tEnter the number you want to find :"; 
    cin>>searchItem; 

     while(loc < listLength && !found) 
        if(list[loc] == searchItem) 
        found = true; 
        else 
        loc++; 
     if(found) 
      cout << "\n\t\t " << searchItem << " is found at index " << loc << endl; 
     else 
      cout << "\n\n\tThe " << searchItem << " is not in the array" << endl; 


getch();  
} 
+0

'listlength'永遠不會被設置爲任何東西。 –

回答

4

讓我們假設4個數組中存在兩個。在你的while循環中,當找到4次時,找到了變量設置爲true。這是循環的破壞條件。正如你寫的:

while(loc < length && !found) 

這就是爲什麼,它只發現一次數字4,它存在兩次。試着解決這個問題。 (提示:你可以使用for循環中,爲便於,或者設置實測值=在每次迭代的結尾假)

而如果元素不是在陣列內,它不確實顯示它的索引。再次仔細嘗試。

編輯: 按照您的要求,您可以這樣做。 更換您,只是你得到這個工作:

int list[5], a, loc = 0, searchItem, listLength; 
bool found = false; 

cout<<"Enter 5 numbers: "<<endl; 
for(a = 0; a < 5; a++) 
      cin >> list[a]; 

cout<<"\n\tEnter the number you want to find :"; 
cin>>searchItem; 



    for(loc = 0;loc < 5; loc++) 
    { 
     if(list[loc]==searchItem) 
     { 
      cout << "\n\t\t " << searchItem << " is found at index"<<loc<<endl; 
     } 
     else 
      cout << "\n\n\tThe " << searchItem << " is not in the array"<<endl; 
    } 
+0

@ Zeeshan - 我該怎麼做?你能給我一個樣品嗎?我只是一個初學者,但我真的很想學習 –

+0

肯定謝謝我會研究你會給我什麼代碼,我會非常感激 –

+0

@AngelCasiMontoya你瞭解空調while循環的概念嗎?你明白爲什麼它找不到整數,它在數組中存在兩次? (順便說一句,如果數組元素是唯一的,你的代碼將會正常工作) – Zeeshan