【发布时间】: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。