2015-02-09 118 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