【问题标题】:c++: searching an arrayc ++:搜索数组
【发布时间】:2020-03-18 15:38:07
【问题描述】:

我正在编写一个程序,它应该搜索一个由用户输入填充的数组,并根据用户给定的另一个整数是否在该数组中返回不同的输出。输出是元素的索引。

例如,假设我的数组是 {1, 2, 3}。使用search(),如果我输入2,它应该告诉我2在数组中并且它的索引值是1

但由于某种原因,这个功能只有在我输入第一个元素时才能正常工作。这意味着如果我在上面的数组中搜索1,它会告诉我索引值是0,就像它应该的那样,但它不会对其他元素这样做。

我的代码如下。我在这里做错了什么?

#include <iostream>

using namespace std;

const int DECLARED_SIZE = 20;

void fillArray(int a[], int size, int& numberUsed);
int search(const int a[], int numberUsed, int target);
int search2(const int a[], int numberUsed, int target);

int main() {
  int size;

  cout << "Enter the array size: ";
  cin >> size;

  int arr[size], listSize, target;

  fillArray(arr, size, listSize);

  char ans;
  int result;

  do {
    cout << "Enter a number to search for: ";
    cin >> target;
    cout << endl << endl;

    result = search(arr, size, target);

    if (result == -1) {

      cout << target << " is not on the list." << endl << endl;
      cout << "Search again? (y/n): ";
      cin >> ans;
      cout << endl << endl;
    }
    else {
      cout << target << " is stored in array position " << result << "." << endl << endl;
      cout << "Search again? (y/n): ";
      cin >> ans;
      cout << endl << endl;
    }

  } while ((ans != 'n') && (ans != 'N'));

  cout << "End of program." << endl;
  return 0;


}

void fillArray(int a[], int size, int& numberUsed) {

  cout << "Enter up to " << size << " non-negative whole numbers." << endl;
  cout << "Mark the end of the list with a negative number." << endl;

  int next, index = 0;

  cin >> next;

  while ((next >= 0) && (index < size)) {

    a[index] = next;
    index++;
    cin >> next;
  }

  numberUsed = index;
}


//searches an array that is filled by the user

//this is where i think i am struggling

int search(const int a[], int numberUsed, int target) {

  int index = 0;
  bool found = false;

  while ((!found) && (index < numberUsed)) {

    if (target == a[index]) {
      found = true;
    }
    else {
      index++;
    }

    if (found) {
      return index;
    }
    else {
      return -1;
    }
  }

  return 0;
}

【问题讨论】:

  • 您正在检查是否在循环内部找到元素,如果没有,则返回-1。因此,您的循环只会迭代一次
  • @Chipster 不,它不是 UB,它只是非标准的,一些编译器支持它作为扩展。
  • @Chipster 这是“格式错误”。
  • 您应该将listSize 传递给search,而不是size

标签: c++ arrays function


【解决方案1】:

如果您查看 search 函数,您会发现它总是在 while 循环的底部返回。这就是为什么你只能找到第一个数字。如果找到号码,您应该做的是返回,但如果没有,请继续。像这样(对你的代码进行一些其他的简化)

int search(const int a[], int numberUsed, int target) {
  for (int index = 0; index < numberUsed; index++) {
    if (target == a[index]) {
      return index;
    }
  }
  return -1;
}

【讨论】:

  • 很好地演示了如何将一些复杂但不起作用的东西变成简单的东西。
【解决方案2】:

在搜索功能的 while 循环中,您正在执行以下操作:

if (found) {
    return index;
} else {
    return -1;
}

这意味着如果您没有找到您的输入,它会立即返回 -1 而不是尝试下一个索引。仅当您访问了所有其他索引后才应返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多