【问题标题】:C++ Calling - search functionC++ 调用 - 搜索功能
【发布时间】:2015-02-09 02:43:12
【问题描述】:

我想知道如何才能完成这个程序。它是在列表“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 应该如何知道ll 中的内容,除非您以某种方式告诉它?此外,ll 是一个糟糕的变量名 - 避免使用 lOI

标签: c++ function call iostream


【解决方案1】:

searchsearch每个参数都有问题:

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

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

【讨论】:

  • 谢谢,不幸的是我还是编程新手。我将学习我的基本功能技能。
【解决方案2】:

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

【讨论】:

  • 如果iit 在函数中立即被覆盖,为什么还要将它们作为参数传递?
  • 你说得对,我没注意,会修改我的程序。
猜你喜欢
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多