C++调用-搜索功能

C++ Calling - search function

本文关键字:功能 搜索 调用 C++      更新时间:2023-10-16

我想知道如何完成这个程序。它是对用户输入的项目It的列表"ll"(长度为31)进行线性搜索,如果找到,则返回用户输入的数字及其位置。

问题:我不知道如何在这个特定的场景中调用函数,我真的不需要使用指针或传递值,所以缺少这些实际上让我更困惑,因为这些都是相当常见的场景。

#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;
}

search:的每个参数都有问题

  • i的传递值在使用之前会被覆盖,因此应该是一个局部变量
  • it也是如此
  • ll应该是int数组
  • 根本没有使用z

printit的情况更糟:4个参数中的3个被忽略。

如果已经打印出结果,则搜索和打印不需要返回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;
}