2015-02-09 100 views
1

我在想如何完成這個程序。在用戶輸入的項目列表「ll」(長度爲31)上執行線性搜索,如果找到,則返回用戶輸入的號碼及其位置。C++調用 - 搜索功能

問題:我不確定如何調用這個特定場景中的函數,我並不需要使用指針或傳遞值,所以缺乏這些讓我更加困惑,因爲那些是相當常見的情況。

#include <iostream> //enables usage of cin and cout 
#include <cstring> 

using namespace std; 

int search (int i, int it, int ll, int z); 
int printit (int i, int it, int ll, int z); 

int main() 
{ 
    int i,it,z; 
    int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers 
    //call to search 
    return 0; 
} 

int search (int i, int it, int ll, int z) 
{ 
    cout << "Enter the item you want to find: "; //user query 
    cin >> it; //"scan" 
    for(i=0;i<31;i++) //search 
    { 
     if(it==ll[i]) 
     { 
     //call to printit 
     } 
    } 
    return 0; 
} 

int printit (int i, int it, int ll, int z) 
{ 
    cout << "Item is found at location " << i+1 << endl; 
    return 0; 
} 
+0

除非您以某種方式告訴它,否則'search'應該知道'll'中的內容?另外,'ll'是一個可怕的變量名 - 避免使用'l','O'和'I'。 – Barry 2015-02-09 02:45:30

回答

0

如果您已經打印出結果,搜索和打印不需要返回int。還有一些聲明變量是無用的。下面的代碼可以工作:

#include <iostream> //enables usage of cin and cout 
#include <cstring> 

using namespace std; 

void search (int ll[]); 
void printit (int n); 

int main() 
{ 
// int i,it,z; 
    int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers 
    //call to search 

    search(ll); 
    return 0; 
} 

void search (int ll[]) 
{ 
    cout << "Enter the item you want to find: "; //user query 
    cin >> it; //"scan" 
    for(i=0;i<31;i++) //search 
    { 
     if(it==ll[i]) 
     { 
      //call to printit 
      printit(i); 
     } 
    } 
// return 0; 
} 

void printit (int n) 
{ 
    cout << "Item is found at location " << n+1 << endl; 
// return 0; 
} 
+1

爲什麼'i'和'it'作爲參數傳遞,如果它們立即被覆蓋在函數中? – 2015-02-09 03:03:56

+0

你是對的,我沒有注意到,會修改我的程序。 – 2015-02-09 03:16:11

+0

非常感謝! – csheroe 2015-02-09 03:24:02

1

沒有與的參數的每個search一個問題:它被使用之前

  • i的傳遞的值被覆蓋,並且因此應該是一個局部變量
  • 相同的東西it
  • ll應該是陣列int小號
  • z完全不

使用的東西,甚至是爲printit糟糕:3的4個參數被忽略。

+0

謝謝,不幸的是我仍然是編程新手。我會研究我的基本功能技能。 – csheroe 2015-02-09 03:22:06